3
4

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.

ビット演算による商(切り捨て)・余り計算

Last updated at Posted at 2020-02-07

ビット演算は低級言語に近いのでどんな言語においても速い.
2 の n 乗での割り算で特に便利.

一般 (JavaScript)

商 : 割り算の解(小数)に対して 0 を OR 演算
(余 : % 演算子を使用, ビット演算じゃない)

ex.17÷6の商と余り
q = (17/6)|0; // 商 = 2
r = 17%6 // 余り = 5

結局途中で小数が発生するからそんなに速くはないが, Math.floor よりは軽い.

2 の n 乗 (1, 2, 4, 8, 16...) での割り算の場合 (JavaScript, Python)

商 : 左へ n ビットシフト
余 : (2^n)-1 で AND 演算

ex.17÷8の商と余り
q = 17>>3; // 商 = 2
r = 17&7; // 余り = 1

ちなみに

バイナリ周り
// N bit のデータを格納するのに必要な byte 数は
byteLength = 1 + ((N-1)>>3);
// Uint8Array の先頭から N ビット目を取り出すには
bitN = uint8array[N>>3] & (1<<(N&7));
3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?