英文:
Java: converting numbers and string to hex returns different results. Why?
问题
尝试将数字转换为十六进制时遇到了困难,看一下:
数字:32
期望的十六进制(ASCII):20
从以字符串形式出现的数字中得到的结果:
System.out.println(String.format("%02x", new BigInteger(1, "32".getBytes(StandardCharsets.US_ASCII))));
给我结果是 3332(我理解这是因为它解析了3(=33)和2(=32))
作为数字进行转换的结果:
System.out.println(Integer.toHexString(32));
给我结果是 20(正确的)
我想更好地理解这个情况,有人可以解释一下彼此之间的区别吗?(请不要说“因为调用了不同的方法...要友好一些)
另外,第一个方法让我设置字符集,而第二个方法则没有。为什么?
英文:
Trying to convert numbers to hex got me stuck, take a look:
Number: 32
Hex expected (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) )
Result converting as number:
System.out.println(Integer.toHexString(32));
Gives me 20 (correct)
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?
答案1
得分: 2
getBytes()
方法的返回值是一个字符串的每个字节,对于你的情况,将是'3'和'2'。
使用String.format("%02x", ...)
来打印它们,会显示它们ASCII码的十六进制数。
另一方面,Integer.toHexString(32)
从toHexString
方法获取数据,而这个方法不会分隔每个单独的字节,而是以十六进制格式获取数据。
英文:
return of getBytes()
method from a String, separates every byte of that String which in your case would be '3' and '2'.
printing them using String.format("%02x", .....
, shows hexadecimal number of their ASCII codes.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论