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
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.
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.
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.
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.
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 };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With