Skip to content

Instantly share code, notes, and snippets.

@ChaunceyHoover
Created October 25, 2021 20:05
Show Gist options
  • Save ChaunceyHoover/0afc9f6a912b2d426518b1f4eaeee4fb to your computer and use it in GitHub Desktop.
Save ChaunceyHoover/0afc9f6a912b2d426518b1f4eaeee4fb to your computer and use it in GitHub Desktop.
Align any given number to the nearest specified amount of bits or bytes
/**
* Returns a number that is n-bits aligned, where n is the number of bits specified
* @param x The input number to be aligned
* @param bits The amount of bits to align the number to
* @returns `x` aligned to the nearest n-bits, where `n` is the specified amount of bits
*/
function alignToBits(x, bits) {
return (x + (bits - 1)) & (-1 * bits);
}
/**
* Returns a number that is n-bytes aligned, where n is the number of bytes specified
* @param x The input number to be aligned
* @param bytes The amount of bytes to align the number to
* @returns `x` aligned to the nearest n-bytes, where `n` is the specified number of bytes
*/
function alignToBytes(x, bytes) {
return alignToBits(x, bytes * 8);
}
/*
EXAMPLES:
==========
// Align numbers to the nearest 8 bit value
alignToBits( 1, 8) => 8
alignToBits( 2, 8) => 8
alignToBits( 3, 8) => 8
// ...
alignToBits( 8, 8) => 8
alignToBits( 9, 8) => 16
alignToBits(10, 8) => 16
// Align numbers to the nearest 2 byte value
alignToBytes( 1, 2) => 16
alignToBytes( 2, 2) => 16
// ...
alignToBytes(15, 2) => 16
alignToBytes(16, 2) => 16
alignToBytes(17, 2) => 32
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment