C语言 如何将负的十六进制转换为十进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25663808/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:20:28  来源:igfitidea点击:

how to convert negative hexadecimal to decimal

cencodingnumbersdecimalnegative-number

提问by karim

hi I want to know how it is possible to convert a hexadecimal negative value (to complement encoding) to decimal, easily without converting hexadecimal to binary and then multiplying each bit in by a power of 2 and sums all the value to get the result, it takes too much time : example of number (32 bits) : 0xFFFFFE58

嗨,我想知道如何将十六进制负值(以补充编码)转换为十进制,而无需将十六进制转换为二进制,然后将每个位乘以 2 的幂并将所有值相加以获得结果,花费太多时间:数字示例(32 位):0xFFFFFE58

so how can I do it?

那我该怎么做呢?

采纳答案by mch

without using a computer you can calculate it like this:

不用电脑,你可以这样计算:

0xFFFF FE58 = - 0x1A8 = -(1 * 162 + 10 * 16 + 8) = -(256 + 160 + 8) = -424

0xFFFF FE58is a negative number in 2's complement. To get the absolute value you have to invert all bits and add 1 in binary. You also can subtract this number from the first number out of range (0x1 0000 0000)

0xFFFF FE58是 2 的补码中的负数。要获得绝对值,您必须反转所有位并在二进制中加 1。您也可以从超出范围的第一个数字中减去此数字 (0x1 0000 0000)

 0x100000000
-0x0FFFFFE58
      =
 0x0000001A8

now we know that your number is -0x1A8. now you have to add up the digits multiplied with their place value. 8 * 16^0 + A (which is 10) * 16^1 + 1 * 16^2 = 424. So the decimal value of your number is -424.

现在我们知道你的号码是-0x1A8。现在您必须将乘以它们的位值的数字相加。8 * 16^0 + A(即 10)* 16^1 + 1 * 16^2 = 424。所以你的数字的十进制值为 -424。

回答by shoham

do a calculation on the positive number, then convert to the negative with Two's complement.

对正数进行计算,然后用二进制补码转换为负数。

see explanation here for positive conversion from hexa to decimal:

有关从六进制到十进制的正转换,请参见此处的说明:

http://www.permadi.com/tutorial/numHexToDec/

http://www.permadi.com/tutorial/numHexToDec/

basically:

基本上:

  1. Get the right most digit of the hex number, call this digit the currentDigit.
  2. Make a variable, let's call it power. Set the value to 0.
  3. Multiply the current digit with (16^power), store the result.
  4. Increment power by 1.
  5. Set the the currentDigit to the previous digit of the hex number.
  6. Repeat from step 3 until all digits have been multiplied.
  7. Sum the result of step 3 to get the answer number.
  1. 获取十六进制数的最右边数字,将此数字称为 currentDigit。
  2. 制作一个变量,我们称之为权力。将该值设置为 0。
  3. 将当前数字乘以 (16^power),存储结果。
  4. 将功率增加 1。
  5. 将 currentDigit 设置为十六进制数的前一位。
  6. 从第 3 步开始重复,直到所有数字都相乘。
  7. 将第 3 步的结果相加得到答案编号。