Bit Math Cheatsheet

These are just a few techniques I've come across for doing bitwise operations in JavaScript. Feel free to leave additions or improvements in the comments.

Turn on first x bits

> (1 << bits) - 1

For example, to obtain 8 bits

> (1 << 8 ) - 1
255 # 11111111  

To obtain 4 bits

> (1 << 4) - 1
15 # 00001111  

Bit mask

Use the & operator to filter bits to only those that are desired

val & mask  

For example, obtain the leftmost 4 bits

> 187 & 240  # 10111011 & 11110000
176          # 10110000  

For example, obtain the middle 4 bits

> 187 & 60   # 10111011 & 00111100
56           # 00111000  

Byte Addition

To create a larger uint from an array of bytes:
1. shift left 8 bits
2. add byte to value via or

let bytes = [130,39,17];  
let val = 0;  
for(let byte of bytes) {  
   val = (val << 8) | byte;
}
comments powered by Disqus