Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split an integer into 2 byte binary?

Tags:

java

Given

private int width = 400;
private byte [] data = new byte [2];  

I want to split the integer "width" into two bytes and load data[0] with the high byte and data[1] with the low byte.

That is binary value of 400 = 1 1001 0000 so data[0] should contain 0000 0001 and data[1] should contain 1001 0000

like image 414
Kevin Boyd Avatar asked Nov 14 '09 22:11

Kevin Boyd


People also ask

How do you divide bytes into integers?

We split the input integer (5000) into each byte by using the >> operator. The second operand represents the lowest bit index for each byte in the array. To obtain the 8 least significant bits for each byte, we & the result with 0xFF .

What is the hex value stored for for 2 byte integer?

That would be 16-number .


4 Answers

Using simple bitwise operations:

data[0] = (byte) (width & 0xFF);
data[1] = (byte) ((width >> 8) & 0xFF);

How it works:

  • & 0xFF masks all but the lowest eight bits.
  • >> 8 discards the lowest 8 bits by moving all bits 8 places to the right.
  • The cast to byte is necessary because these bitwise operations work on an int and return an int, which is a bigger data type than byte. The case is safe, since all non-zero bits will fit in the byte. For more information, see Conversions and Promotions.

Edit: Taylor L correctly remarks that though >> works in this case, it may yield incorrect results if you generalize this code to four bytes (since in Java an int is 32 bits). In that case, it's better to use >>> instead of >>. For more information, see the Java tutorial on Bitwise and Bit Shift Operators.

like image 65
Stephan202 Avatar answered Oct 08 '22 22:10

Stephan202


For converting two bytes the cleanest solution is

data[0] = (byte) width;
data[1] = (byte) (width >>> 8);

For converting an integer to four bytes the code would be

data[0] = (byte) width;
data[1] = (byte) (width >>> 8);
data[2] = (byte) (width >>> 16);
data[3] = (byte) (width >>> 24);

It doesn't matter whether >> or >>> is used for shifting, any one bits created by sign extension will not end up in the resulting bytes.

See also this answer.

like image 27
starblue Avatar answered Oct 08 '22 23:10

starblue


This should do what you want for a 4 byte int. Note, it stores the low byte at offset 0. I'll leave it as an exercise to the reader to order them as needed.

public static byte[] intToBytes(int x) {
    byte[] bytes = new byte[4];

    for (int i = 0; x != 0; i++, x >>>= 8) {
        bytes[i] = (byte) (x & 0xFF);
    }

    return bytes;
}
like image 42
Taylor Leese Avatar answered Oct 08 '22 21:10

Taylor Leese


Integer is 32 bits (=4 bytes) in java, you know?

width & 0xff will give you the first byte, width & 0xff00 >> 8 will give you the second, etc.

like image 21
Dmitry Avatar answered Oct 08 '22 21:10

Dmitry