0

I have 2 bytes in a byte array, and I'd like to "merge" them together so as to get byte 2's binary appended to byte 1's binary, and then get the decimal value of that binary.

byte 1: 01110110 byte 2: 10010010

combined gives 16 bits: 0111011010010010.

desired output: 30354

I am doing it like this right now, but wanted to know if there's a way that doesn't involve strings?

StringBuilder combined = new StringBuilder();
byte[] buffer = new byte[2];

buffer[0] = input[i];
buffer[1] = input[i + 1];

combined.append(Integer.toBinaryString(buffer[0] & 255 | 256).substring(1));
combined.append(Integer.toBinaryString(buffer[1] & 255 | 256).substring(1));

int key = Integer.parseInt(combined.toString(), 2);

Thanks!

vimdiesel
  • 15
  • 1
  • 3
  • Your "byte 1" is 9 bits long, which exceeds the amount of bits in a `byte`. Are you able to provide a better example of what you want to achieve? – Jacob G. Feb 02 '21 at 23:04
  • @JacobG. Sorry that was just a typo mistake. Fixed. – vimdiesel Feb 02 '21 at 23:05
  • *Is there a more efficient way to combine 2 bytes and get the resulting decimal value?* yes, obviously without converting it to string and back – Selvin Feb 02 '21 at 23:09
  • 1
    Does this answer your question? [Read two bytes into an integer?](https://stackoverflow.com/questions/4768933/read-two-bytes-into-an-integer) – Selvin Feb 02 '21 at 23:20

1 Answers1

-1

To concatenate two bytes together efficiently, some bitwise arithmetic is required. However, to achieve the result that you want, we need to operate on the bytes as int values, as the result may be represented by more than 8 bits.

Consequently, we need to ensure that we're always working with the least significant 8 bits of each value (keep in mind that negative integers are represented using leading 1s in binary instead of 0s).

This can be accounted for by performing a bitwise-and of each value with 0xFF:

byte higher = (byte) 0b01110110;
byte lower = (byte) 0b10010010;

int concatenated = ((higher & 0xFF) << 8) | (lower & 0xFF);

System.out.println(concatenated);

As expected, the output of this snippet is:

30354
Jacob G.
  • 28,856
  • 5
  • 62
  • 116