新人Y子のプログラミングのお部屋19

2の補数について続きです

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]前回のおさらいですが、コンピュータでは、マイナス値を「2の補数」で表現し、-1は2進数で「11111111」(*1)となるのでしたよね。
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい。[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]でも、普通に「00000000」から1ずつ足していっても、「11111111」にたどり着きますよね?
+と-はどこで区別すればいいんですか?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]最上位のビットが1になっているものがすべてマイナスの値になります。
2の補数表現で、プラス側の最大値は「01111111」(=127)になります。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]なるほど、最上位ビットが符号でしたね。
あと、「01111111」が、127という事をどうやって確かめられますか?[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]10進数と同じように、2進数でも各桁に重みがあるので、「1」になっている桁に対応する重みを合計すれば出るんです。
最下位桁 = 2の0乗(=1)
 1桁目 = 2の1乗(=2)
 2桁目 = 2の2乗(=4)
 3桁目 = 2の3乗(=8)
 4桁目 = 2の4乗(=16)
 5桁目 = 2の5乗(=32)
 6桁目 = 2の6乗(=64)
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]試しに、「01111111」は・・・?
1+2+4+8+16+32+64なので、127 ですね!
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]では、先ほどと逆の方法で、10進数から2進数の変換もやってみましょう。[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]70を2進数にしてください。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]1,2,4,8,16,32,64,128,・・・から選ぶ訳ですよね。
64 + 4 + 2で 70 になりますね。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-bikkuri.png" name="新人Y子"]「64」と「4」と「2」の重みに対応する桁に1を立てて、「01000110」ですか?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]正解です!
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="techtrageman-normal.png" name="テクトレージマン"]次回に続く[/speech_bubble]

(*1) char型の場合

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

目次