How do I split an integer into 2 byte binary?

前端 未结 7 1251
再見小時候
再見小時候 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:32

    To get the high byte, shift right by 8 bits then mask off the top bytes. Similarly, to get the low byte just mask off the top bytes.

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

提交回复
热议问题