skip to Main Content

I convert a decimal number into binary. My number is 66. I convert it like:

let bin1 = Number(66).toString(2);
console.log(`Result: ${bin1}, Length: ${bin1.length}`);

The result I get is bin1 = 1000010. So I get only 7 bits of the byte. I want to get all 8 bits of byte. So, I should get 01000010. What should I do to get so?

3

Answers


  1. Insert zero’s until the stringified value length is a multiple of 8. For example:

    console.log(getFullBytes(66));
    console.log(getFullBytes(255));
    console.log(getFullBytes(1024));
    console.log(getFullBytes(100000));
    
    function getFullBytes(number) {
      let bin = number.toString(2);
      
      while (bin.length % 8 !== 0) {
        bin = `0${bin}`;
      }
      
      return bin;
    }
    Login or Signup to reply.
  2. You will have to pad your number:

    console.log((66).toString(2).padStart(8, '0')); // 01000010

    Here is a formatter with documentation:

    /**
     * Calculates the min number of bits required to represent a given int.
     *
     * @param {number} n - The int to evaluate.
     * @returns {number} The min number of bits needed to represent the int.
     */
    const calculateMinBits = (n) => {
      if (n === 0) return 1; // Handle zero separately since log2(0) is undefined
      return Math.floor(Math.log2(Math.abs(n))) + 1;
    };
    
    /**
     * Formats a number to a binary string with a specified min number of bytes.
     *
     * @param {number} n - The number to format.
     * @param {number} [byteCount=1] - The number of bytes to represent the number in binary.
     * @returns {string} The binary string representation of the number.
     * @throws {Error} If the number requires more bits than provided in the byte length.
     */
    const formatBinaryString = (n, byteCount = 1) => {
      const totalBits = byteCount * 8;  // Calculate total bits from the number of bytes
      const requiredBits = calculateMinBits(n);  // Determine min bits required for number
    
      // If min required bits exceed the bits available in specified bytes, throw an error
      if (requiredBits > totalBits) {
        throw new Error(`Number ${n} requires ${requiredBits} bits, but ${totalBits} bits are insufficient`);
      }
      // Convert to a binary string, padding with zeroes on the left to match the total bit length
      return n.toString(2).padStart(totalBits, '0');
    };
    
    // Example usage
    console.log(formatBinaryString(66));         // Outputs: 01000010
    console.log(formatBinaryString(66, 2));      // Outputs: 0000000001000010
    console.log(formatBinaryString(0xFF, 1));    // Outputs: 11111111
    console.log(formatBinaryString(0xFFFF, 2));  // Outputs: 1111111111111111
    
    try {
      formatBinaryString(0x100, 1)
    } catch (e) {
      // Outputs: Number 256 requires 9 bits, but 8 bits are insufficient
      console.log(e.message);
    }
    Login or Signup to reply.
  3. So I get only 7 bits of the byte. I want to get all 8 bits of byte.

    toString(2) is unaware of the notion of byte, which is why the returned string does not necessarily have a number of digits that is a multiple of 8. It is expected that the returned string will always start with a "1", except when the input integer is 0 (assuming unsigned integers).

    I should get 01000010. What should I do to get so?

    You can use padStart to pad the string with the zeroes you need to get a multiple of 8:

    function toBinary8(unsignedInt) {
        const s = unsignedInt.toString(2);
        return s.padStart(s.length + (8 - s.length%8) % 8, "0");
    }
    
    for (const unsignedInt of [17, 255, 256, 5215, 65535, 1234567]) {
        console.log(unsignedInt, toBinary8(unsignedInt));
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search