How do I split an integer into 2 byte binary?

前端 未结 7 1236
再見小時候
再見小時候 2020-12-12 22:22

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]

相关标签:
7条回答
  • 2020-12-12 22:49

    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.

    0 讨论(0)
提交回复
热议问题