Java中,int轉byte陣列
阿新 • • 發佈:2018-12-30
private static final int COMMAND_NO_READ_RESOURCE = 0x0224;
HexUtil.intToBytes(COMMAND_NO_READ_RESOURCE, 2)
/** * Transform integer array to byte * @param source * the source need to be transformed * @param length * the length of byte array * @return b the length of byte array b*/ public static byte[] intToBytes(int source, int length) { byte[] b = new byte[length]; for (int i = 0; i < length; i++) { b[i] = (byte) (source >> 8 * (length - i - 1) & 0xFF); } return b; }
(source >> 8 * (length - i - 1) & 0xFF);是將int轉為2位位元組的陣列。
參考連結如下:
https://my.oschina.net/u/169390/blog/97495
http://blog.csdn.net/sunnyfans/article/details/8286906