convert a number from base 2 to base 16 in javascript

To convert a number from base 2 to base 16 in JavaScript, we can follow the following algorithm:

  1. First, we need to split the binary number into groups of 4 bits each, starting from the rightmost side. If the number of bits is not a multiple of 4, then we can add leading zeros to the left until it becomes a multiple of 4. For example, if the binary number is '10111', we can add one leading zero to get '010111', and then split it into '0101' and '1100'.

  2. Next, we need to convert each group of 4 bits into its corresponding hexadecimal digit. We can use a lookup table, or simply write a switch statement to map the binary value to a hexadecimal digit. For example, '0000' corresponds to '0', '0001' corresponds to '1', ..., '1011' corresponds to 'B', '1100' corresponds to 'C', ..., and '1111' corresponds to 'F'.

  3. Finally, we need to join the hexadecimal digits together to get the final result. We can use the Array.join() method to concatenate the digits into a single string.

Here's the JavaScript code that implements this algorithm:

index.tsx
function binToHex(bin) {
  // add leading zeros to make the length a multiple of 4
  while (bin.length % 4 !== 0) {
    bin = '0' + bin;
  }

  let hex = '';
  for (let i = 0; i < bin.length; i += 4) {
    const nibble = bin.substr(i, 4);
    switch (nibble) {
      case '0000': hex += '0'; break;
      case '0001': hex += '1'; break;
      case '0010': hex += '2'; break;
      case '0011': hex += '3'; break;
      case '0100': hex += '4'; break;
      case '0101': hex += '5'; break;
      case '0110': hex += '6'; break;
      case '0111': hex += '7'; break;
      case '1000': hex += '8'; break;
      case '1001': hex += '9'; break;
      case '1010': hex += 'A'; break;
      case '1011': hex += 'B'; break;
      case '1100': hex += 'C'; break;
      case '1101': hex += 'D'; break;
      case '1110': hex += 'E'; break;
      case '1111': hex += 'F'; break;
    }
  }

  return hex;
}
896 chars
32 lines

We can then use this function to convert a binary number to hexadecimal format:

index.tsx
console.log(binToHex('101010')); // prints '2A'
console.log(binToHex('111011010010')); // prints '3B2'
console.log(binToHex('101')); // prints '5'
147 chars
4 lines

gistlibby LogSnag