问题
I'm a little lost on this. I need to use two fractional bits
0.(a-1)(a-2)
Like that, now I can use .00 .01 .10
and .11
But I need negative numbers (in 2's complement) also, so would .10
be -.5
? or would it be -.25
?
The same with .11
, that would be -.75
? or would it be -.5
?
I'm pretty sure it would be the former in both cases, but I'm not entirely positive.
回答1:
In two's complement notation, all of the most significant bits of a negative number are set to 1. Let's assume you're storing these numbers as 8 bits, with 2 to the right of the "binary point."
By definition, x + -x = 0
, so we can write:
0.5 + -0.5 = 0.10 + 111111.10 = 0 // -0.5 = 111111.10
0.25 + -0.25 = 0.01 + 111111.11 = 0 // -0.25 = 111111.11
0.75 + -0.75 = 0.11 + 111111.01 = 0 // -0.75 = 111111.01
and so on.
Using 8 bits like this, the largest number you can store is
011111.11 = 31.75
the least-positive number is
000000.01 = 0.25
the least-negative number is
111111.11 = -0.25
and the smallest (that is, the most negative) is
100000.00 = -32
回答2:
see it this way:
you have normal binary representation
let's assume 8 bit words ...
the first bit (MSB) has the value 128, the second 64, and so on ...
in other words the first bit (MSB) is 2^7 ... the second bit is 2^6 ... and the last bit is 2^0
now we can assume our 8 bit word has 2 decimal places ....
we now start with the first bit (MSB) 2^5 and end with the last bit beeing 2^-2
no magic here ...
now to turn that into binary complement: simply negate the value of the first bit
so instead of 2^5 it would be -2^5
so base 10 -0.75 would be in binary complement
111111.01 ...
(1*(-32) + 1*16 + 1*8 + 1*4 + 1*2 +1*1 + 0*0.5 + 1*0.25)
(1*(-2^5) + 1*2^4 + 1*2^3 + 1*2^2 + 1*2^1 +1*2^0 + 0*2^(-1) + 1*2^(-2))
回答3:
A number stored in two's complement inverts the sign of the uppermost bit's magnitude (so that for e.g. a 16-bit number, the upper bit is -32768 rather than +32768). All other bits behave as normal. Consequently, when performing math on multi-word numbers, the upper word of each number should be regarded as two's-complement (since its uppermost bit will be the uppermost bit of the overall number), but all other words in each number should be regarded as unsigned quantities.
For example, a 16-bit two's complement number has place values (-32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, and 1). Split into two 8-bit parts, those parts will have place values (-32768, 16384, 8192, 4096, 2048, 1024, 512, and 256); and (128, 64, 32, 16, 8, 4, 2, and 1). The first set of values is in a two's complement 8-bit number, times 256; the latter set is an unsigned 8-bit number.
来源:https://stackoverflow.com/questions/9946183/2s-complement-representation-of-fractions