Skip to content

Instantly share code, notes, and snippets.

@colxi
Created May 14, 2018 23:47
Show Gist options
  • Save colxi/8e02a369048ab68a2d8f71031adadfaa to your computer and use it in GitHub Desktop.
Save colxi/8e02a369048ab68a2d8f71031adadfaa to your computer and use it in GitHub Desktop.
/**
* The individual bits of 'x' are named b7, b6, b5, b4, b3, b3, b2, b1 and b0.
* The bit b7 is the sign bit (the most significant bit), and b0 is the least significant.
* x = byte(s) to operate with
* n = number of bit to manipulate
* v = new value to the bit
*/
/**
* The idea here is that an integer is odd if and only if the least significant bit b0 is 1.
* It follows from the binary representation of 'x', where bit b0 contributes to either 1 or 0.
* By AND-ing 'x' with 1 we eliminate all the other bits than b0. If the result after this
* operation is 0, then 'x' was even because bit b0 was 0. Otherwise 'x' was odd.
*/
function isEven(x){
return ( (x & 1) == 0 ) ? true : false;
}
/**
* Test if n-th bit is set. It does it by shifting that first 1-bit n positions to the
* left and then doing the same AND operation, which eliminates all bits but n-th.
*/
function isBitSet(x,n){
return (x & (1<<n)) ? true : false;
}
/**
* Set the specified bit(n) to 1 or 0 (v) in the binary representation of the provided value(x)
*/
function setBit(x,n,v){
/**
* Set the bit to 1
* combines the same (1<<n) trick of setting n-th bit by shifting with OR operation.
* The result of OR-ing a variable with a value that has n-th bit set is turning that n-th bit on.
* It's because OR-ing any value with 0 leaves the value the same; but OR-ing it
* with 1 changes it to 1 (if it wasn't already).
*/
if(v) return ( x | (1<<n) );
/**
* Set tht bit to 0
* The important part of this bithack is the ~(1<<n) trick. It turns on all the bits except n-th.
* The effect of AND-ing variable 'x' with this quantity is eliminating n-th bit.
* It does not matter if the n-th bit was 0 or 1, AND-ing it with 0 sets it to 0.
*/
else return ( x & ~(1<<n) );
}
/**
* This bit hack also uses the wonderful "set n-th bit shift hack" but this time it XOR's it with the
* variable 'x'. The result of XOR-ing something with something else is that if both bits are the same,
* the result is 0, otherwise it's 1. How does it toggle n-th bit? Well, if n-th bit was 1, then XOR-ing
* it with 1 changes it to 0; conversely, if it was 0, then XOR-ing with with 1 changes it to 1. See, the
* bit got flipped.
*/
function toggleBit(x,n){
return ( x ^ (1<<n) );
}
@colxi
Copy link
Author

colxi commented May 14, 2018

You can find many many other bit hacks in:
http://graphics.stanford.edu/~seander/bithacks.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment