How to Convert a Number to Bytes in JavaScript

08/01/2021

Contents

In this article, you will learn how to convert a number to bytes in JavaScript.

Converting a number to bytes in JavaScript

Converting a number to bytes involves converting the number to its binary representation and then breaking it down into bytes, which are 8-bit sequences of 0s and 1s. In JavaScript, this can be done using the toString() method to convert the number to binary and then splitting it into 8-bit chunks.

Here are the steps to convert a number to bytes in JavaScript:

Convert the number to binary using the toString() method with a radix of 2 (binary). This will return a string of 0s and 1s representing the binary value of the number.

const num = 255;
const binary = num.toString(2); // "11111111"

If the binary string’s length is not divisible by 8, pad it with leading zeros to make it a multiple of 8. This is necessary because each byte must be 8 bits long.

let paddedBinary = binary.padStart(Math.ceil(binary.length / 8) * 8, '0'); // "0000000011111111"

Split the padded binary string into 8-bit chunks using the match() method with a regular expression that matches every 8 characters.

const bytes = paddedBinary.match(/.{1,8}/g); // ["00000000", "11111111"]

Convert each byte from binary to decimal using the parseInt() method with a radix of 2.

const decimalBytes = bytes.map(byte => parseInt(byte, 2)); // [0, 255]

The resulting decimalBytes array contains the byte values in decimal format.

Here’s an example function that encapsulates these steps:

function numberToBytes(num) {
  const binary = num.toString(2);
  const paddedBinary = binary.padStart(Math.ceil(binary.length / 8) * 8, '0');
  const bytes = paddedBinary.match(/.{1,8}/g);
  const decimalBytes = bytes.map(byte => parseInt(byte, 2));
  return decimalBytes;
}

const num = 255;
const bytes = numberToBytes(num); // [0, 255]

This function takes a number as input and returns an array of bytes in decimal format. You can modify the function to return the bytes in hexadecimal or binary format if desired.