0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

シフト演算

Posted at

シフト演算

左右にビットをずらして(シフトして)、乗算や除算の演算をすること
符号を考慮しない論理シフトと、符号を考慮する算術シフトがある。
nビット左にシフト - 2ⁿ 倍
nビット右にシフト - ½ⁿ 倍

論理シフト

符号を考慮しないシフト演算
左・右シフトとも、あふれたビットは捨て、空いたビットには0が入る。

論理左シフト

例:2進数100 = 10進数4
・論理左シフト(2ビット)
00000100 -> 00|00010000
緑のとこは捨てられ、青にとこは空きに入った0
大きさは4倍になったので、2進数10000 = 10進数16となる。

論理右シフト

例:2進数100 = 10進数4
・論理右シフト(2ビット)
00000100 -> 00000001|00
緑のとこは捨てられ、青にとこは空きに入った0
大きさは¼倍になったので、2進数1 = 10進数1となる。

算術シフト

符号を考慮するシフト演算
左・右で空きビットの扱い方が違う

算術左シフト

・算術左シフト(2ビット)4倍
符号ビットはそのままの位置に留まり、あふれたビットは捨て、空きには0が入る。
※符号ビット - 最上位にある、正(0)・負(1)を表すビット。

例:2進数 11111100 = 10進数 -4
11111100 -> 11|11110000
緑のとこは捨てられ、青にとこは空きに入った0。赤は符号ビットなのでそのまま
結果は2進数11110000 = 10進数-16となる

算術右シフト

・算術右シフト(2ビット)¼倍
符号ビットはそのままの位置に留まり、あふれたビットは捨て、空きには符号ビットと同じビットが入る。
例:2進数 11111100 = 10進数 -4
11111100 -> 11111111|00
緑のとこは捨てられ、青にとこは空きに入った符号ビットと同じビット。赤は符号ビットなのでそのまま
結果は2進数11111111 = 10進数 -1となる

シフト演算と加算の組合わせ

例:2進数100(4)の9倍の値を求める。()内は10進数
00000100(4) -> 00100000(32) - この時点で3ビット論理左シフトしたので、8倍している
9倍するにはここに、2進数100自身を足せば良い。よって00100100(36)となる。

00000100 * 2³ + 00000100 = 00100100

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?