将整数转换为字节数组(Java)

148

如何快速将 Integer 转换为 Byte Array

例如:0xAABBCCDD => {AA, BB, CC, DD}


2
结果的字节数组的格式是否重要呢?您对它有什么计划? - skaffman
11个回答

-1

这是我的解决方案:

public void getBytes(int val) {
    byte[] bytes = new byte[Integer.BYTES];
    for (int i = 0;i < bytes.length; i ++) {
        int j = val % Byte.MAX_VALUE;
        bytes[i] = (j == 0 ? Byte.MAX_VALUE : j);
    }
}

还有一个关于 String 的方法:

public void getBytes(int val) {
    String hex = Integer.toHexString(val);
    byte[] val = new byte[hex.length()/2]; // because byte is 2 hex chars
    for (int i = 0; i < hex.length(); i+=2)
        val[i] = Byte.parseByte("0x" + hex.substring(i, i+2), 16);
    return val;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接