将两个二进制数的补码转换成十进制数。

时间:2022-11-08 11:48:02

I'm wondering how you could convert a two's complement in fix-point arithmetic to a decimal number.

我想知道你如何把小数点后两位的补数转换成小数。

So let's say we got this fix-point arithmetic in two's complement: 11001011 with bit numbering, with 2 positions behind the decimal point, and want form it to a decimal number.

假设我们得到了这个点算术,它是2的补码:11001011加上位号,小数点后面有2个位置,要把它化成小数。

We already know that the decimal will be negative because the first bit is a 1.

我们已经知道小数是负的因为第一个位是1。

2 positions behind decimal point, so we have 110010 11.

小数点后面有2个位置,所以是110010 11。

Convert that from two's complement to normal form (sub by 1, invert):

将它从2的补数转换成正态形式(下标1,反式):

110010 10 (i sub by 1 here)

110010 (i下标1)

001101 01 (i inverted here)

001101 01(我倒在这里)

001101 in decimal is 13

小数点后的001101是13

01 in decimal is 1

0。01是1

So in the end we get to -13.1. Is that correct or there isn't even a way to convert this?

最后得到-13。1。这是正确的吗?还是根本就没有转换的方法?

1 个解决方案

#1


1  

The simplest method is just to convert the whole value to an integer (ignoring the fixed point, initially), then scale the result.

最简单的方法是将整个值转换为整数(最初忽略不动不动点),然后缩放结果。

So for your example where you have a 6.2 fixed point number: 110010 10:

在你的例子中,你有一个6。2定点数:110010:

Convert as integer:

转换为整数:

11001010 = -54

Divide by scale factor = 2^2:

除以比例因子= 2 ^ 2:

-54 / 4 = -13.5

Note that the fractional part is always unsigned. (You can probably see now that 10 would give you + 0.5 for the fractional part, i.e. 00 = 0.0, 01 = +0.25, 10 = +0.5, 11 = +0.75.)

注意,小数部分总是无符号的。(你现在可能会看到10对小数部分是+0.5,也就是00 = 0.0,01 = +0.25,10 = +0.5,11 = +0.75)

#1


1  

The simplest method is just to convert the whole value to an integer (ignoring the fixed point, initially), then scale the result.

最简单的方法是将整个值转换为整数(最初忽略不动不动点),然后缩放结果。

So for your example where you have a 6.2 fixed point number: 110010 10:

在你的例子中,你有一个6。2定点数:110010:

Convert as integer:

转换为整数:

11001010 = -54

Divide by scale factor = 2^2:

除以比例因子= 2 ^ 2:

-54 / 4 = -13.5

Note that the fractional part is always unsigned. (You can probably see now that 10 would give you + 0.5 for the fractional part, i.e. 00 = 0.0, 01 = +0.25, 10 = +0.5, 11 = +0.75.)

注意,小数部分总是无符号的。(你现在可能会看到10对小数部分是+0.5,也就是00 = 0.0,01 = +0.25,10 = +0.5,11 = +0.75)