Last active
October 19, 2020 09:23
-
-
Save mvidaldp/fab65cd3e432df003dd19550f9df342d to your computer and use it in GitHub Desktop.
How to decode signed and unsigned 12 and 24-bit encoded integers from a byte array in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For unsigned integers, all byte array elements are decoded as unsigned using (value & 0xff) before the left shift (<<) | |
private static int byteArrayToUInt(byte[] input) { | |
if (input.length == 3) { // 24-bit encoded | |
// always decode them starting from right to left (2, 1, 0 indices in this example) | |
return (input[0] & 0xFF) << 16 | (input[1] & 0xFF) << 8 | (input[2] & 0xFF); // lowercase F(f) also works | |
} else if (input.length == 2) { // 12-bit encoded | |
return (input[0] & 0xFF) << 8 | (input[1] & 0xFF); | |
} | |
} | |
// For the signed integers, all the same, except that the right-most element is directly left shifted (<<) without unsigning | |
private static int byteArrayToSInt(byte[] input) { | |
if (input.length == 3) { // 24-bit encoded | |
return (input[0]) << 16 | (input[1] & 0xFF) << 8 | (input[2] & 0xFF); | |
} else if (input.length == 2) { // 12-bit encoded | |
return (input[0]) << 8 | (input[1] & 0xFF); | |
} | |
} | |
// Extracted from: | |
// - https://stackoverflow.com/a/14856974 | |
// - https://stackoverflow.com/a/5399829 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment