Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Need functions to convert a string containing binary to hex, then convert back to binary

Lets say I have a string in JavaScript with binary data in it. It may look like this:

var binary = '00001000010001000101010100001110';

I need some reliable functions to convert this into a hexadecimal string, and then convert back from that hexadecimal to a binary string again. I know about the following functions

// Convert binary to hexadecimal
var hex = parseInt(binaryCharacters, 2).toString(16);

// Convert hexadecimal to binary
var binary = parseInt(hex, 16).toString(2)

But I'm not sure how to convert the whole string at once. Am I right in understanding I need to convert each 4 binary bits at a time into a single hexadecimal character? Then to get back to binary I loop through each hexadecimal character and convert to binary again?

I have hunted for some simple examples doing this in JavaScript but can't find any.

Many thanks

like image 479
user2503552 Avatar asked Jun 20 '13 03:06

user2503552


People also ask

How do you convert from hexadecimal to binary?

Hexadecimal to binarySplit the hex number into individual values. Convert each hex value into its decimal equivalent. Next, convert each decimal digit into binary, making sure to write four digits for each value. Combine all four digits to make one binary number.

Can hex convert to binary directly?

Thus, the conversion of hexadecimal to binary is very important. Here it is not possible to convert it directly, we will convert hexadecimal to decimal then that decimal number is converted to binary.

How do you convert a string to a binary number?

The idea is to first calculate the length of the string as n and then run a loop n times. In each iteration store ASCII value of character in variable val and then convert it into binary number and store result in array finally print the array in reverse order.

Why is it easy to convert between hexadecimal and binary?

Converting between hex and binary is easy, because each digit of a hexadecimal number "maps" to four bits (a bit being an individual binary digit) of a binary value. So a byte -- eight binary digits -- can always be represented by two hexadecimal digits.


1 Answers

Try this jsfiddle.

The more interesting functions to you are here. Not necessarily the cleanest or most efficient ones, but yea:

// converts binary string to a hexadecimal string
// returns an object with key 'valid' to a boolean value, indicating
// if the string is a valid binary string.
// If 'valid' is true, the converted hex string can be obtained by
// the 'result' key of the returned object
function binaryToHex(s) {
    var i, k, part, accum, ret = '';
    for (i = s.length-1; i >= 3; i -= 4) {
        // extract out in substrings of 4 and convert to hex
        part = s.substr(i+1-4, 4);
        accum = 0;
        for (k = 0; k < 4; k += 1) {
            if (part[k] !== '0' && part[k] !== '1') {
                // invalid character
                return { valid: false };
            }
            // compute the length 4 substring
            accum = accum * 2 + parseInt(part[k], 10);
        }
        if (accum >= 10) {
            // 'A' to 'F'
            ret = String.fromCharCode(accum - 10 + 'A'.charCodeAt(0)) + ret;
        } else {
            // '0' to '9'
            ret = String(accum) + ret;
        }
    }
    // remaining characters, i = 0, 1, or 2
    if (i >= 0) {
        accum = 0;
        // convert from front
        for (k = 0; k <= i; k += 1) {
            if (s[k] !== '0' && s[k] !== '1') {
                return { valid: false };
            }
            accum = accum * 2 + parseInt(s[k], 10);
        }
        // 3 bits, value cannot exceed 2^3 - 1 = 7, just convert
        ret = String(accum) + ret;
    }
    return { valid: true, result: ret };
}

// converts hexadecimal string to a binary string
// returns an object with key 'valid' to a boolean value, indicating
// if the string is a valid hexadecimal string.
// If 'valid' is true, the converted binary string can be obtained by
// the 'result' key of the returned object
function hexToBinary(s) {
    var i, k, part, ret = '';
    // lookup table for easier conversion. '0' characters are padded for '1' to '7'
    var lookupTable = {
        '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100',
        '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001',
        'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101',
        'e': '1110', 'f': '1111',
        'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101',
        'E': '1110', 'F': '1111'
    };
    for (i = 0; i < s.length; i += 1) {
        if (lookupTable.hasOwnProperty(s[i])) {
            ret += lookupTable[s[i]];
        } else {
            return { valid: false };
        }
    }
    return { valid: true, result: ret };
}
like image 129
yanhan Avatar answered Sep 18 '22 23:09

yanhan