Skip to content

Instantly share code, notes, and snippets.

@ratchit
Last active December 13, 2015 19:49
Show Gist options
  • Save ratchit/4965687 to your computer and use it in GitHub Desktop.
Save ratchit/4965687 to your computer and use it in GitHub Desktop.
Bitmask convenience functions in JavaScript.
// Return the value of one offset bit in mask
function bit_query( mask, bit ) {
return ( ( mask & ( 1 << bit ) ) >> bit );
}
// Return input mask with offset bit switched ON
function bit_on( mask, bit ) {
return ( mask | ( 1 << bit ) );
}
// Return input mask with offset bit switched OFF
function bit_off( mask, bit ) {
return ( mask & ~( 1 << bit ) );
}
// Return input mask with offset bit TOGGLED
function bit_toggle( mask, bit ) {
return ( mask ^ ( 1 << bit ) );
}
// Return decimal input in binary form
function dec2bin( dec ) {
for ( var out = new String; dec; dec >>= 1 )
out = new String( dec & 1 ).concat( out );
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment