怎样将int转换为byte

  • Post author:
  • Post category:其他


一个int占用4个byte,所以需要声明一个4位长度的byte数组

public byte[] int2Byte2(int i) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) ((i >> 24) & 0xff);
        bytes[1] = (byte) ((i >> 16) & 0xff);
        bytes[2] = (byte) ((i >> 8) & 0xff);
        bytes[3] = (byte) (i & 0xff);
        return bytes;
    }
i的值 1 类型转换byte后
原码 0000 0000 0000 0000 0000 0000

0000 0001
>>24 0000 0000 0000 0000 0000 0000

0000 0000
0000 0000
>>16 0000 0000 0000 0000 0000 0000

0000 0000
0000 0000
>>8 0000 0000 0000 0000 0000 0000

0000 0000
0000 0000

0xff:0x表示16进制,后边的ff表示15*15=255,也就是1111 1111,当进行&操作时,会先将自己补位(变为int类型),也就是 0000 0000 0000 0000 0000 0000 1111 1111

&操作规则:https://blog.csdn.net/m0_47759414/article/details/107148516

这里是先进行移位再进行&操作,最后进行强转byte,此处我认为进行&操作是没必要的,因为&操作的主要目的就是将低八位以外的位置进行置0操作,但是进行强制类型转换byte后,只需要保留低八位,那么其余位置的数据是有没有置0,又有什么关系呢。

但是看到了一块apache的源码进行转换时,也进行了&操作,所以到底什么场景会用到&操作呢?

    /**
     * Returns the integer represented by up to 4 bytes in network byte order.
     * 
     * @param buf the buffer to read the bytes from
     * @param start
     * @param count
     * @return
     */
    public static int networkByteOrderToInt(byte[] buf, int start, int count) {
        if (count > 4) {
            throw new IllegalArgumentException("Cannot handle more than 4 bytes");
        }
 
        int result = 0;
 
        for (int i = 0; i < count; i++) {
            result <<= 8;
            result |= (buf[start + i] & 0xff);
        }
 
        return result;
    }
 
    /**
     * Encodes an integer into up to 4 bytes in network byte order.
     * 
     * @param num the int to convert to a byte array
     * @param count the number of reserved bytes for the write operation
     * @return the resulting byte array
     */
    public static byte[] intToNetworkByteOrder(int num, int count) {
        byte[] buf = new byte[count];
        intToNetworkByteOrder(num, buf, 0, count);
 
        return buf;
    }
 
    /**
     * Encodes an integer into up to 4 bytes in network byte order in the 
     * supplied buffer starting at <code>start</code> offset and writing
     * <code>count</code> bytes.
     * 
     * @param num the int to convert to a byte array
     * @param buf the buffer to write the bytes to
     * @param start the offset from beginning for the write operation
     * @param count the number of reserved bytes for the write operation
     */
    public static void intToNetworkByteOrder(int num, byte[] buf, int start, int count) {
        if (count > 4) {
            throw new IllegalArgumentException("Cannot handle more than 4 bytes");
        }
 
        for (int i = count - 1; i >= 0; i--) {
            buf[start + i] = (byte) (num & 0xff);
            num >>>= 8;
        }
    }



版权声明:本文为m0_47759414原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。