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

引き続き、2進数のお勉強をします。

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]2進数の引き算をしてみましょう。
10進数の「7」は、2進数(*1)で「00000111」でした。
ここから、1づつ引いていって下さい。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]7は、「00000111」なので、
6は、「00000110」
5は、「00000101」(2桁目繰り下がり)
4は、「00000100」
3は、「00000011」(3桁目繰り下がり)
2は、「00000010」
1は、「00000001」(2桁目繰り下がり)
0は、「00000000」ですか?
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]2進数の繰り下がりが正しくできており、引き算も完璧ですね。
それでは、今日の本題、「2の補数」を使用したマイナス値の表現をしましょう。
まずは、「-1」からです。
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]先ほど、1づつ引いていき、「0000000」になりましたが、更に1を引いて、「-1」を考えてみましょう。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]これ以上、引けないのでは?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]ここから先も、2の補数で表現できるんです。
その方法を説明しますね。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]はい、お願いします。[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]まず、引こうとする数を、一時的に9ビットとみなしてください。
その9ビット目は、「1」を立ててください。

ここから、1を引いてみてください。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]「100000000」 から 「1」を引くのですね?
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい。「100000000」からであれば、1を引くことができると思います。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]答えは、「011111111」ですか?
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]その通りです。では、ここから、下位8ビットだけ取り出してください。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]「11111111」ですか?
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい、これが、2の補数表現での「-1」です。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]へぇ~
では「-2」はどうなりますか?
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]「11111111」から、1を引くことで出ます。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]「11111110」になりますか?

[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい。それが「-2」です。
同様に、
-3は、「11111101」
-4は、「11111100」
-5は、「11111011」
:
という風に表現されます。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]へぇ〜[/speech_bubble]

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

*1) 8ビット整数型(char型)の場合

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

この記事を書いた人

目次