🏠 Games Tutorials Dev blog JS code golf Other projects

Binary operations

September 2012

Binary operations in JavaScript are a trap. I wrote a wtfjs post about this. (link)
So I wrote a 137 bytes lib allowing to do "left shifts", "right shifts", and extracting some bits from a number, safely.

M=Math // Math alias
function l(a,b){return a*M.pow(2,b)} // Left shift
function r(a,b){return M.floor(a/M.pow(2,b))} // Right shift
function b(a,b,c){return r(a,b)&M.pow(2,c-b+1)-1} // Bit extraction

2022 update: ES6 version (73 bytes)

l=(n,o)=>n*2**o // Left shift
r=(n,o)=>~~(n/2**o) // Right shift
b=(n,o,a)=>r(n,o)&2**(a-o+1)-1 // Bit extraction

Source code:

// M is a shortcut for Math
M = Math;

// Left shift
// a << b is equivalent to a * (2 ^ b)
function l(a,b){
  return a * M.pow(2, b);
}

// Right shift
// a >> b is equivalent to a / (2 ^ b)
function r(a,b){
  return M.floor(a / M.pow(2, b));
}

// Bit extraction
// returns a's bits from b to c
// i.e. the last (c - b + 1) bits of (a >> b)
function b(a,b,c){
  return r(a,b) & M.pow(2, c - b + 1) - 1;
}