Merge Two Bytes to Int

Merge two bytes to int

Mathematical approach

double digitCount = Math.floor(Math.log10(b2) + 1.0);
int result = b1 * (int) Math.pow(10, digitCount) + b2;

Iterative approach (slice one digit at a time from right to left)

int result = 0;
int digit, multiplier = 1;
int base = b2;
while (base > 0) {
digit = base % 10;
base /= 10;
result += digit * multiplier;
multiplier *= 10;
}

base = b1;
while (base > 0) {
digit = base % 10;
base /= 10;
result += digit * multiplier;
multiplier *= 10;
}

Straightforward approach (concatenate as strings and parse)

int result = Integer.parseInt("" + b1 + b2);

Is there a more efficient way to combine 2 bytes and get the resulting decimal value?

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

Convert 2 bytes into an integer

I receive a port number as 2 bytes (least significant byte first)

You can then do this:

  int number = buf[0] | buf[1] << 8;

Combining two bytes in Python

Left-shift the second byte by 8 bits and bitwise OR it with the first byte:

(second_byte << 8) | first_byte

For extra safety clamp both bytes to [0, 255] with a bitwise AND:

((second_byte & 0xFF) << 8) | (first_byte & 0xFF)

combine/merge two bytes into one...?

uint16_t value = (highByte << 8) | lowByte ;

Convert two bytes to a signed integer in java

Two bytes as a signed integer:

public class MyClass {
public static void main(String args[]) {
byte h = (byte)0xff;
byte l = (byte)0xf9;

int i = (short) ((h << 8) | l);
System.out.println(i);
}
}

(I'll paste the comment I made under your question here):

Use a short instead, because the leftmost bit of your int is 0, therefore it is a positive number. But if you use a short, then you'll get the negative value you want, because the type short only have 2 bytes, then the leftmost bit will be the leftmost 1 in 0xFF, making it a negative number.



Related Topics



Leave a reply



Submit