How do I split an integer into 2 byte binary?

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

    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.

    0 讨论(0)
  • 2020-12-12 22:30

    I suggest you have a look at the source for HeapByteBuffer. It has the conversion code for all primitive data types. (In fact you could just use a ByteBuffer ;)

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-12 22:36
    int width = 400;
    byte [] data = new byte [2];
    
    data[0] = (byte) ((width & 0xFF00) >> 8);
    data[1] = (byte) (width & 0xFF);
    
    for(int b = 0; b < 2; b++) {
        System.out.println("printing byte " + b);
        for(int i = 7; i >= 0; i--) {
            System.out.println(data[b] & 1);
            data[b] = (byte) (data[b] >> 1);
        }
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-12 22:41

    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.

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