0

I have an array of 4 bytes I would like to join them to get the complete number in java code

for example:

byte[0] = 1d (in hexa) = 00011101 (in binary)
byte[1] = 32 = 00110010 
byte[2] = d1 = 11010001
byte[3] =0x5 = 00000101

I would like to get = 00000101110100010011001000011101 = 9759593 (integer)

  1. how do I add the zeros if needed? (like in byte[1] in the example)
  2. how do I combine them to one number?
Ohad
  • 1,563
  • 2
  • 20
  • 44

1 Answers1

1

You can use binary operators in Java to archive that.

First, you should convert your bytes to 32-bit integer and make sure that values (like byte[2]) are all evaluated as unsigned values (means in range 0-255). You can do both by & 0xFF them.

Than you can do the zero-adding by shifting them to the left.

Finally, you can just connect them by OR them together.

int value =
  ((byte[3] & 0xFF) << 24) |
  ((byte[2] & 0xFF) << 16) |
  ((byte[1] & 0xFF) << 8) |
  ((byte[0] & 0xFF) << 0)
Cryptjar
  • 1,079
  • 8
  • 13