java - 长到字节数组无效
问题描述
我开始使用字节和十六进制来尝试更轻松地存储一些数据。这就是我目前正在做的事情:
byte[] data = new byte[] {0x20, 0x40};
long cosmetics = 0;
for(byte d : data) {
cosmetics = cosmetics | d;
System.out.println(d + ": " + cosmetics);
}
String hex = Long.toHexString(cosmetics);
System.out.println("hex: 0x" + hex);
System.out.println("from hex: " + Long.decode("0x"+hex));
byte[] bytes = longToBytes(cosmetics);
String s = "";
for(byte b : bytes)
s += b+", ";
System.out.println("bytes: " + s);
这一切都很好,hex: 0x60
并且from hex = 96
,就像它应该是(afaik)一样。
但是,当我尝试将 96 转换回字节数组时,使用longToBytes(cosmetics)
:
public static byte[] longToBytes(long x) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(x);
return buffer.array();
}
它不返回我最初使用的数组,它给出:0, 0, 0, 0, 0, 0, 0, 96
但我希望它给我的是我最初使用的数组:
byte[] data = new byte[] {0x20, 0x40};
解决方案
long 有 8 个字节,您将字节 0x20|0x40 = 0x60 = 96 as long 放入数组中。
Java 默认对字节进行排序 bigendian,因此最低有效字节 96 排在最后。
反过来做:
public static byte[] longToBytes(long x) {
return ByteBuffer.allocate(Long.BYTES)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(x)
.array();
}
应该给
96, 0, 0, 0, 0, 0, 0, 0
提炼后的问题
无法确定 96 源自 0x20|0x40,但我假设您需要单独的位掩码。
byte[] longToBytes(long x) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int mask = 1;
for (int i = 0; i < 8; ++i) {
if ((mask & x) != 0) {
baos.write(0xFF & (int)mask);
}
mask <<= 1;
}
return baos.toArray();
}
该参数可以/应该是一个字节或 0-256 受限 int 以获得合理的结果。
推荐阅读
- assembly - 在 x86 asm 中添加 32 位错误字节序数
- javascript - 正则表达式只允许整数和小数点数字
- powerbi - 我可以使用 PowerBI Query 发送用户 ID/电子邮件吗?
- r - method.args=list(family=binomial) 在 R 中是什么意思?
- where-clause - 我想使用 HTML Canvas 显示多个带圆角的图像。我想结合下面的两个程序
- python - 使用 Python 监控特定 Android 像素的颜色
- list - 在 Prolog 中设置两个兼容列表的差异
- excel - 连接可变数量的字段
- javascript - 从展开的气泡动画中删除背景图像
- java - 找不到符号类位置