java中2的十六进制数到十进制的补码
我有一个表示 2 的补码数的十六进制字符串。有没有一种简单的方法(库/函数)可以将十六进制转换为十进制而不直接使用其位?
EG 这是左边十六进制的预期输出:
"0000" => 0
"7FFF" => 32767 (max positive number)
"8000" => -32768 (max negative number)
"FFFF" => -1
谢谢!
I have a hex string that represents a 2's complement number. Is there an easy way (libraries/functions) to translate the hex into a decimal without working directly with its bits??
E.G. This is the expected output given the hex on the left:
"0000" => 0
"7FFF" => 32767 (max positive number)
"8000" => -32768 (max negative number)
"FFFF" => -1
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这似乎欺骗java转换数字而不强制得到正结果:
当然这种事情只适用于8、16、32和64位2的补码:
示例如下。
This seems to trick java into converting the number without forcing a positive result:
Of course this sort of thing only works for 8, 16, 32, and 64-bit 2's complement:
Example here.
只需编写一个实用方法:
测试:
Just write a utility method:
Tests:
这似乎运作得相当不错。它可以通过传递非标准长度字符串来欺骗它:“FFF”映射到-1。零填充将纠正错误。
您不清楚您想要什么类型的返回,所以我返回了
Number
,无论大小合适。示例输出:
This seems to work reasonably well. It can be fooled by passing it non-standard length strings: "FFF" maps to -1. Zero padding will correct the fault.
You are not clear on what type return you want, so I have returned
Number
, at whatever size is appropriate.Sample output: