Skip to content

Instantly share code, notes, and snippets.

@samuelfvlcastro
Last active April 22, 2024 20:59
Show Gist options
  • Save samuelfvlcastro/b24bece0a38ed5734d2e1123bf85ca40 to your computer and use it in GitHub Desktop.
Save samuelfvlcastro/b24bece0a38ed5734d2e1123bf85ca40 to your computer and use it in GitHub Desktop.
Example of a bit field in javascript. Packing RGBA values into a single 32bit integer
function logBinary(number){
console.log((number >>> 0).toString(2).replace(/(.{8})/g, " "));
}
var startBit = 8;
var bitsToGet = 8;
var alpha = 45;
var red = 187;
var green = 255;
var blue = 56;
// [ ALPHA ] [ RED ] [ GREEN ] [ BLUE ]
// 8bit + 8bit + 8bit + 8bit = 32bits
// Starts: 24th 16th 8th 0
var argb = (alpha << 24) | (red << 16) | (green << 8) | blue;
logBinary(argb);
// For unpacking a bitfield we use bitwise operations
// In this case we use a mask with a AND to strip the required bits
// (1 << x) - 1) - shifts the first "x" bits
// ((1 << x) - 1) << y - transverses the start of the shift "y" bits
var unpackingMask = ((1 << bitsToGet) - 1) << startBit
var unpackedBits = argb & unpackingMask;
logBinary(unpackedBits);
// Removes the tailing zeros left from the unpacking
// Shifts the bits to the start
var decimalValue = unpackedBits >> startBit
// After the last shift we are left if the required decimal number
console.log(decimalValue);
@brandonetter
Copy link

This was an incredibly helpful demonstration ty

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