LoginSignup
2
2

More than 5 years have passed since last update.

javascriptのint, uint計算

Posted at

javascriptでint, uintで計算をやる方法のまとめ。

javascriptで32bit整数(int, uint)で計算する方法。
intは-2147483648+2147483647
uintは04294967295

bit演算

jsではbit演算の結果は32bit符号有り整数(int)になる。

let a = 0xffff; // (+65535)
let b = 0x00ff; // (+255)

// and演算
console.log(a & b); // 0x00ff (+255)
// or演算
console.log(a | b); // 0xffff (+65535)
// xor演算
console.log(a ^ b); // 0xff00 (+65280)
// not演算
console.log(^a); // 0xffff0000 (-65536)

※not演算の補足
0xffff0x0000ffffなので、bit反転すると0xffff0000となり負数になる。

シフト演算

let a = 0x0000ffff; // (+65535)
let b = 0xffff0000; // (-65536)

// 左シフト
console.log(a << 8); // 0x00ffff00 (+16776960)
console.log(b << 8); // 0xff000000 (-16777216)
// 符号維持右シフト
console.log(a >> 8); // 0x000000ff (+255)
console.log(b >> 8); // 0xffffff00 (-256)
// 0埋め右シフト
console.log(a >>> 8); // 0x000000ff (+255)
console.log(b >>> 8); // 0x00ffff00 (+16776960)

応用

javascriptではbit演算を行うとその戻り値は32bit符号有り整数(int)になる。
ただし0埋め右シフトは例外で、32bit符号無し整数(uint)になる。

let bignum = 0xffffff000000; // (+281474959933440)

// 32bitに切り詰められて、符号有り
console.log(bignum | 0); // 0xff000000 (-16777216)
// 32bitに切り詰められて、符号無し
console.log(bignum >>> 0); // 0xff000000 (+4278190080)

32bit同士の数値の演算としてMath.imulが用意されており、サポートされているブラウザでは利用できる。

let a = 0x40000000; // (+1073741824)
let b = 0x3fffffff; // (+1073741823)
// 普通に掛け算すると誤差が生じる
console.log(a * b); // 0xfffffffc0000030 (+1152921503533105200)
// Math.imulを利用すると戻り値が32bit符号有り整数になる
console.log(Math.imul(a, b)); // 0xc0000000 (-1073741824)
// 0埋め右シフトと併用することでuintとして演算できる
console.log(Math.imul(a, b) >>> 0); // 0xc0000000 (+3221225472)
2
2
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
2
2