Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 24-bit number signing

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

like image 292
Tony Avatar asked Feb 13 '13 15:02

Tony


People also ask

What is 24-bit integer?

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).

What is 0x00800000?

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.

What is 16bit offset?

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.

How many bits have integer?

Integer, 16 bit Unsigned data type is used for numerical tags where only positive variables will be used.


2 Answers

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);
    }
}
like image 176
Joop Eggen Avatar answered Oct 22 '22 16:10

Joop Eggen


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);
like image 2
Jon Skeet Avatar answered Oct 22 '22 17:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!