Java 24 bit number signing

I am currently working on some work with 24 bit integers.

Basically, I need to be able to get both signed and unsigned values ​​from those 24-bits.

I am currently using the following code to concatenate three bytes and return their value to me.

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 give it is bytes: 0x42 0x87 0xfe

and the result returned is:16680770

This is (I believe) the correct unsigned value, however I also need its signed value, which I think is -96446

I guess I need to do a bit of work on this, but I'm not sure how.

I tried to make the result in and long, but it didn't return the signed value. I have also tried Math.abs (result) but I don't think I am using that correctly.

Any input would be appreciated.

thank

+3


source to share


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);
    }
}

      



+4


source


One option is only 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);

      

+2


source







All Articles