How do I split an integer into 2 byte binary?

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

    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;
    }
    

提交回复
热议问题