简体   繁体   English

Java:将数字和字符串转换为十六进制会返回不同的结果。 为什么?

[英]Java: converting numbers and string to hex returns different results. Why?

Trying to convert numbers to hex got me stuck, take a look:试图将数字转换为十六进制让我卡住了,看看:

Number: 32数量:32

Hex expected (ASCII): 20十六进制预期(ASCII):20

Result from number that came as string:以字符串形式出现的数字的结果:

System.out.println(String.format("%02x", new BigInteger(1, "32".getBytes(StandardCharsets.US_ASCII))));

Gives me 33 32 as result (which I understood that happens because it parses 3 (=33) and 2 (=32) )给我 33 32 结果(我理解这是因为它解析 3 (=33) 和 2 (=32) )

Result converting as number:结果转换为数字:

System.out.println(Integer.toHexString(32));

Gives me 20 (correct)给我20(正确)

I would like to better understand this situation, can someone explain what differs from each other?我想更好地了解这种情况,有人可以解释一下彼此之间有什么不同吗? (please don't say "because it calls different methods... be friendly) (请不要说“因为它调用不同的方法......友好)

Also, the first approach lets me set the Charset and the second one doesn't.此外,第一种方法可以让我设置字符集,而第二种方法则不能。 Why?为什么?

return of getBytes() method from a String, separates every byte of that String which in your case would be '3' and '2'.从字符串返回getBytes()方法,分隔该字符串的每个字节,在您的情况下为“3”和“2”。

printing them using String.format("%02x", ..... , shows hexadecimal number of their ASCII codes.使用String.format("%02x", .....打印它们,显示其 ASCII 代码的十六进制数。

in the other hand, Integer.toHexString(32) gets data from toHexString method and this method does not separate every single byte and gets data in hexadecimal format.另一方面, Integer.toHexString(32)toHexString方法获取数据,该方法不分隔每个字节,而是以十六进制格式获取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM