私は2の補数を理解しようとしています:
2 の補数は、この数値が無効であることを意味しますか?
1000
2 の補数では、正の数に最上位ビットを使用することはできませんか? すなわち。できる
1000
2^3 を表現したことはありますか? それとも-0を表しますか?
また、1 の補数に 1 を追加する必要がある理由についても混乱しています。
私は2の補数を理解しようとしています:
2 の補数は、この数値が無効であることを意味しますか?
1000
2 の補数では、正の数に最上位ビットを使用することはできませんか? すなわち。できる
1000
2^3 を表現したことはありますか? それとも-0を表しますか?
また、1 の補数に 1 を追加する必要がある理由についても混乱しています。
2's complement is mostly a matter of how you interpret the value, most math* doesn't care whether you view a number as signed or not. If you're working with 4 bits, 1000 is 8 as well as -8. This "odd symmetry" arises here because adding it to a number is the same as xoring it with a number (since only the high bit is set, so there is no carry into any bits). It also arises from the definition of two's complement - negation maps this number to itself.
In general, any number k
represents the set of numbers { a | a = xk mod n }
where n
is 2 to the power of how many bits you're working with. This perhaps somewhat odd effect is a direct result of using modular arithmetic and is true whether you view number as signed or unsigned. The only difference between the signed and unsigned interpretations is which number you take to be the representative of such a set. For unsigned, the representative is the only such a
that lies between 0 and n
. For signed numbers, the representative is the only such a
that lies between -(n/2)
and (n/2)-1
.
As for why you need to add one, the goal of negation is to find an x'
such that x' + x = 0
. If you only complemented the bits in x
but didn't add one, x' + x
would not have carries at any position and just sum to "all ones". "All ones" plus 1 is zero, so adding one fixes x'
so that the sum will go to zero. Alternatively (well it's not really an alternative), you can take ~(x - 1)
, which gives the same result as ~x + 1
.
*Signedness affects the result of division, right shift, and the high half of multiplication (which is rarely used and, in many programming languages, unavailable anyway).
2 の補数では、MSB (最上位ビット) は負の場合に 1 に設定されます。2 の補数に -1 を掛けるには、次のようにします。
数に1を追加します。 最初のビットの後のすべてのビットを逆にします。
例: 1 を追加した後
の数値:を逆にすると: が得られます。
つまりマイナス13です。10010
10011
01101
10010
1000
1 を追加した後の数は:1001
反転後:0111
です。
つまり1000
マイナス7です。
さて、あなたの最後の質問に:いいえ。2 の補数を使用する場合、MSB を正の数に使用することはできません。ただし、2 の補数を使用していないと定義し、より大きな正の数を使用することができます。
2 の補数は、次の 2 つの要件に基づいています。
たとえば、4 ビット表現を想定すると、次のようになります。
0 + -0 = 0000 + -0000 (base 2) = 0000 => -0000 = 0000
1 + -1 = 0001 + -0001 (base 2) = 0000 => -0001 = 1111 (carry falls off the end)
これで構成要素ができました。帰納法を少し説明すると、正の数を 2 の補数の負の表現に変換するために必要なものがまさに「ビットを反転して 1 を加える」アルゴリズムであることがわかります。
数値を表すために使用するビット数によって異なります。
左端 (最大) ビットの値は -1*(2**N-1)、この場合は -8 です。(N はビット数です。) 後続のビットは通常の値です。
そう
1000
-8です
1111
-1 0111 は 7 です。
ただし、8 ビットの場合、これらは異なる値になります。0000 1000
は正の 8 です。左端のビットだけが負の値を答えに追加します。
どちらの場合も、数値の範囲は 1000....0 です。
-2**(N-1) の場合、N ビットで
0111....1 これは 2**(N-1) -1 です。(左端のビットが 0 であるため、これは通常の基数 2 です。)