I'm currently doing some work that has me working with some 24-bit integers.
Essentially I need to be able to get both the signed, and unsigned values from these 24-bits.
Currently I'm using the following code to put the three bytes together and return me their value.
private static int bytesToInt(byte[] input) {
if (input.length == 3) {
return (input[2] & 0xFF) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
}
}
The input I'm giving it are the bytes: 0x42 0x87 0xfe and the returned result is: 16680770
This (I believe) is the correct unsigned value, however I also need the signed value of it, which I think is -96446
I'm guessing I'll have to do some bitshifting here to solve it, but I'm not sure how to accomplish this.
I've tried casting the result into an and a long, but neither return the signed value. I've also tried Math.abs(result), but I don't think I'm using that correctly.
Any input would be appreciated.
Thanks
24-bit refers to twenty-four binary (0 or 1) units of integer data. This allows for up to 16,777,216 combinations of values. 24-bit color can allow for up to 16,777,216 colors, split into three sets of 8-bit values for 256 levels per RGB channel (red, green, and blue).
0x00800000 corresponds to the MSB of the third byte (i.e. the byte in byteArray[0] that was shifted 16 bits left in the previous process). This also corresponds to the MSB of the whole 24-bit value.
An offset is a relative address in some stream and/or storage medium. A 16bit offset is an offset that's stored in a 16 bit variable/slot. So if some file format specification says that "the next field is the 16 bit offset" that means you must read the next 2 byte and treat it as a relative address.
Integer, 16 bit Unsigned data type is used for numerical tags where only positive variables will be used.
private static int bytesToUInt(byte[] input) {
if (input.length == 3) {
return (input[2] & 0xFF) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
}
}
private static int bytesToSInt(byte[] input) {
if (input.length == 3) {
return (input[2]) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
}
}
One option is just to fill the top 8 bits with 1:
int x = 16680770;
int y = x | 0xff000000;
System.out.println(y); // -96446
Or you can just subtract 1 << 24:
int y = x - (1 << 24);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With