JSFiddle - React, Tailwind, and code Playground
JavaScript
/* const num = 0xfffffff; */
const num = 0xf000;
// This is your chunking functions
const getChunks = (num) => [
(num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
(num & 0x000000ff)
];
// We will need a logarithm with base 16 since you are working with hexadecimals
const BASE_16 = Math.log(16);
const log16 = (num) => Math.log(num) / BASE_16;
// This is a function that gives you the number of non-zero chunks you get out
const getNumChunks = (num) => {
// First we grab the base-16 logarithm of the number, that will give us the number of places
// you need to left-shift 16 to get your number.
const numNonZeroes = Math.round(log16(num));
// We need to divide that number by 2 since you are grabbing bits by two
const numChunks = Math.ceil(numNonZeroes / 2);
return numChunks;
}
const getNumChunksBitwise = (num) => {
let slice = 0xff;
let numChunks = 0;
while ((slice & num) || num > slice) {
slice = slice << 8;
numChunks++;
}
return numChunks;
}
console.log(getNumChunks(num), getChunks(num));