Skip to content

Instantly share code, notes, and snippets.

@Aravin
Last active August 31, 2020 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aravin/011f17528f90be6bb4f5a4cb253647d6 to your computer and use it in GitHub Desktop.
Save Aravin/011f17528f90be6bb4f5a4cb253647d6 to your computer and use it in GitHub Desktop.
Javascript Code to Convert Larger Binary Digit to Hex Code

To convert large binary to hex use this code

const binaryData:=
{
    '0000': '0',
    '0001': '1',
    '0010': '2',
    '0011': '3',
    '0100': '4',
    '0101': '5',
    '0110': '6',
    '0111': '7',
    '1000': '8',
    '1001': '9',
    '1010': 'A',
    '1011': 'B',
    '1100': 'C',
    '1101': 'D',
    '1110': 'E',
    '1111': 'F',
};

export function binaryToHex(bin: string)
{
    let hex = '';

    for (let i = 0; i < bin.length;)
    {
        hex = hex + binaryData[bin.substr(i, 4) + ''];
        i += 4;
    }

    return hex;
}

INPUT

00100000001110000000000000000000000000101000000000000000000000000000000000000000000000000000000000000000000000000000000000000010 OUTPUT

20380000028000000000000000000002

Catch: Input should be multiple of 4. Else prefix with zeros.

@Aravin
Copy link
Author

Aravin commented Aug 31, 2020

export function binaryToHex(bin: string)
{
    // prefix zeros
    const missingZeros = 4 - bin.length % 4;

    bin = '0'.repeat(missingZeros) + bin;

    let hex = '';

    for (let i = 0; i < bin.length;)
    {
        hex = hex + parseInt('' + bin.substr(i, 4), 2).toString(16);
        i += 4;
    }

    return hex;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment