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

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]おさらいです。
char型で表現できる最大の値を、2進数で答えてください。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]たしか、最上位のビットが「1」になっているものがマイナスでしたので、
最上位ビットが「0」で残りのビットが「1」の「01111111」が最大でしたよね。
[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい。その通り「01111111」(=127)がchar型で表現できる最大値です。

[/speech_bubble]
[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]では、逆にchar型で表現できる最小値は何になるでしょう?
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]マイナスなので、最上位のビットが「1」であることは想像できますが、その他のビットは・・・分かりません!
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]それでは、「-1」から1ずつ引いてchar型の最小値を確かめてみましょう。
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]まず、「-1」は、char型の2進数で何でしたか?
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]-1は確か「11111111」でしたよね?[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]はい。その通りです。
では、「11111111」から1を引いていってみましょう。
-1 は、「11111111」
-2 は、「11111110」
-3 は、「11111101」
-4 は、「11111100」
-5 は、「11111011」
    :
-125は、「10000011」
-126は、「10000010」
-127は、「10000001」
-128は、「10000000」
-129は、「01111111」 ・・・ 最上位ビットが0になったので、-129は表現できないことになります。
よって、char型の最小値は、「10000000」(=-128)という事になります。
[/speech_bubble]

[speech_bubble type="std" subtype="R1" icon="sanoyu-hatena.png" name="新人Y子"]char型で表現できる値の範囲は、
最小-128
最大127
になるのですね。でも、何でプラスの方が、1つ少ないのかしら?
[/speech_bubble]

[speech_bubble type="std" subtype="L1" icon="itokuma-normal.png" name="しげちゃん先生"]それは、0があるためです。
0は、当然ながら全ビット「0」で表現されますので最上位の符号ビットも「0」です。
最上位ビットが「1」になっているものは、マイナスの値のみですが、
最上位ビットが「0」になっているものは、プラスの値だけでなくとゼロの場合もあるため、プラス側が表現できる数が1つ少なくなるのです。
[/speech_bubble]
[speech_bubble type="std" subtype="R1" icon="sanoyu-normal.png" name="新人Y子"]なるほど。あと、-128〜127の範囲しか表せないとなると、色々と厳しくないですか?
[/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]

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

この記事を書いた人

目次