【发布时间】:2011-11-04 18:09:30
【问题描述】:
如何将 ASCII 值转换为十六进制和二进制值(不是它们在ASCII 中的字符串表示形式)?例如,如何将十进制值 26 转换为 0x1A?
到目前为止,我已经尝试使用以下步骤进行转换(实际代码见下文):
- 将值转换为字节
- 将每个字节转换为 int
- 通过
String.toString(intValue, radix)将每个整数转换为十六进制
注意:我确实问过一个关于 writing hex values to a file. 的相关问题
Clojure 代码:
(apply str
(for [byte (.getBytes value)]
(.replace (format "%2s" (Integer/toString (.intValue byte) 16)) " " "0")))))
Java 代码:
Byte[] bytes = "26".getBytes();
for (Byte data : bytes) {
System.out.print(String.format("%2s", Integer.toString(data.intValue(), 16)).replace(" ", "0"));
}
System.out.print("\n");
【问题讨论】: