如何在java中将ASCII转换为十六进制值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2711264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert ASCII to hexadecimal values in java
提问by lakshmi
How to convert ASCII to hexadecimal values in java.
如何在java中将ASCII转换为十六进制值。
For example:
例如:
ASCII: 31 32 2E 30 31 33
Hex: 12.013
ASCII:31 32 2E 30 31 33
十六进制:12.013
回答by Michael Aaron Safyan
It's not entirely clear what you are asking, since your "hex" string is actually in decimal. I believe you are trying to take an ASCII string representing a double and to get its value in the form of a double, in which case using Double.parseDoubleshould be sufficient for your needs. If you need to output a hex string of the double value, then you can use Double.toHexString. Note you need to catch NumberFormatException, whenever you invoke one of the primitive wrapper class's parse functions.
您在问什么并不完全清楚,因为您的“十六进制”字符串实际上是十进制的。我相信您正在尝试采用代表双精度的 ASCII 字符串并以双精度形式获取其值,在这种情况下,使用Double.parseDouble应该足以满足您的需求。如果需要输出 double 值的十六进制字符串,则可以使用Double.toHexString。请注意,每当您调用原始包装类的解析函数之一时,您都需要捕获NumberFormatException。
byte[] ascii = {(byte)0x31, (byte)0x32, (byte)0x2E, (byte)0x30, (byte)0x31, (byte)0x33}; String decimalstr = new String(ascii,"US-ASCII"); double val = Double.parseDouble(decimalstr); String hexstr = Double.toHexString(val);
回答by polygenelubricants
You did not convert ASCII to hexadecimal value. You had char
values in hexadecimal, and you wanted to convert it to a String
is how I'm interpreting your question.
您没有将 ASCII 转换为十六进制值。您有char
十六进制值,并且您想将其转换为 a 这String
就是我解释您的问题的方式。
String s = new String(new char[] {
0x31, 0x32, 0x2E, 0x30, 0x31, 0x33
});
System.out.println(s); // prints "12.013"
If perhaps you're given the string, and you want to print its char
as hex, then this is how to do it:
如果给定了字符串,并且想将其打印char
为十六进制,则可以这样做:
for (char ch : "12.013".toCharArray()) {
System.out.print(Integer.toHexString(ch) + " ");
} // prints "31 32 2e 30 31 33 "
You can also use the %H
format string:
您还可以使用%H
格式字符串:
for (char ch : "12.013".toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "