java整數和byte陣列之間的轉換
阿新 • • 發佈:2019-01-02
做的程式有時候會需要用到,
記錄下
public class NumberUtil { /** * int整數轉換為4位元組的byte陣列 * * @param i * 整數 * @return byte陣列 */ public static byte[] intToByte4(int i) { byte[] targets = new byte[4]; targets[3] = (byte) (i & 0xFF); targets[2] = (byte) (i >> 8 & 0xFF); targets[1] = (byte) (i >> 16 & 0xFF); targets[0] = (byte) (i >> 24 & 0xFF); return targets; } /** * long整數轉換為8位元組的byte陣列 * * @param lo * long整數 * @return byte陣列 */ public static byte[] longToByte8(long lo) { byte[] targets = new byte[8]; for (int i = 0; i < 8; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((lo >>> offset) & 0xFF); } return targets; } /** * short整數轉換為2位元組的byte陣列 * * @param s * short整數 * @return byte陣列 */ public static byte[] unsignedShortToByte2(int s) { byte[] targets = new byte[2]; targets[0] = (byte) (s >> 8 & 0xFF); targets[1] = (byte) (s & 0xFF); return targets; } /** * byte陣列轉換為無符號short整數 * * @param bytes * byte陣列 * @return short整數 */ public static int byte2ToUnsignedShort(byte[] bytes) { return byte2ToUnsignedShort(bytes, 0); } /** * byte陣列轉換為無符號short整數 * * @param bytes * byte陣列 * @param off * 開始位置 * @return short整數 */ public static int byte2ToUnsignedShort(byte[] bytes, int off) { int high = bytes[off]; int low = bytes[off + 1]; return (high << 8 & 0xFF00) | (low & 0xFF); } /** * byte陣列轉換為int整數 * * @param bytes * byte陣列 * @param off * 開始位置 * @return int整數 */ public static int byte4ToInt(byte[] bytes, int off) { int b0 = bytes[off] & 0xFF; int b1 = bytes[off + 1] & 0xFF; int b2 = bytes[off + 2] & 0xFF; int b3 = bytes[off + 3] & 0xFF; return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; } }