0

My question is about Java int data structure.

If I have a buffer of 4 bytes

byte[] buffer = {(byte)A, (byte)B, (byte)C, (byte)D};

How to build a positive and a negative int values using this array and logic operators (&, |, <<, >>)?

Say int = 4 and int = 130; and -4 and -130.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Rubik
  • 41
  • 5

1 Answers1

2

to construct 32 bit value from four 8 bit values you need to know Endianness

if we assume that high bits are stored into first byte, then you can do:

int v = 0;
for (int i=0; i<4; i++)
    v = (v<<8) | (buffer[i]&0xff);

if high bits are stored in last byte, then you need to reverse loop

int v = 0;
for (int i=3; i>=0; i--)
    v = (v<<8) | (buffer[i]&0xff);
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57