java - 如何在两个字节中转换超过 256 的十六进制值
问题描述
我正在尝试将大于 255(无符号)的十六进制值存储到两个字节中。下面是示例代码:
public class Test {
public static void main(String[] args) {
byte b = (byte)0x12c; // output : 44
System.out.println(b);
}
}
示例:当我将 300 转换为十六进制时,它将是 12c,它应该以字节为 (44, 1)。为什么java在第一个字节中保存44?
解决方案
byte[] bytes = new byte[2];
ByteBuffer bbuf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN):
bbuf.putShort((short) 0x12c);
byte[] bytes = new byte[4];
ByteBuffer bbuf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN):
bbuf.putInt(0x12c);
System.out.println(Arrays.toString(bytes));
或者你自己计算。
在这里,我们创建了我们想要的两个字节,在它周围包裹了一个 ByteBuffer,这样我们就可以读取和写入几个数字原始类型。你想要小端字节顺序(首先是 2c)。
推荐阅读
- php - 如果他没有用户,如何删除部门
- javascript - 将电子表格中的数据作为登录表单的凭据
- neo4j - 如何找到具有大于或等于 n 个标签的所有节点?
- powershell - Powershell 帮助多个用户
- spring - Google 日历 API 以编程方式提供对 gservice 帐户的访问权限
- html - 同一页面上的多个引导模式轮播,不起作用
- npm - 如何从 npmjs 获取我的包的最新版本
- node.js - NuxtServerError,状态码为 500,但错误消息涉及 401 错误
- flutter - 在 http.get() 中使用列表
- json - 我可以将嵌套的 json 解组为平面结构吗