How to Convert ASCII to Hexadecimal in JavaScript
- Convert an ASCII Character to Hexadecimal in JavaScript
- Converting a String of ASCII Into Hexadecimal Equivalent in JavaScript
- Convert Hexadecimal Back to ASCII
- Remarks
The main intention to develop the American Standard Code for Information Interchange (ASCII) was to exchange data between devices. ASCII is a code table that has human-readable characters and it consists of each character mapped to specific numbers (the so-called ASCII codes). Like the binary base number systems used by computers, we use hexadecimal number systems while transmitting data over a channel for error-free communication. ASCII is a human-readable format, which is internally used differently by computers. Let’s see how we can convert an ASCII value to a hex value with JavaScript.
Convert an ASCII Character to Hexadecimal in JavaScript
The conversion is easy and doesn’t require many steps in the code. Let us look at the code for converting an ASCII character to hexadecimal.
window.onload =
function() {
convertASCIItoHex('A');
convertASCIItoHex('n');
convertASCIItoHex('!');
}
function convertASCIItoHex(asciiVal) {
let asciiCode = asciiVal.charCodeAt(0);
let hexValue = asciiCode.toString(16);
console.log('0x' + hexValue);
}
Output:
0x41
0x6e
0x21
In this section, we are dealing with converting an ASCII character into the hexadecimal equivalent for it. We have the conversion process explained as follows.
-
In the
window.onload()
function of javascript, we call theconvertASCIItoHex()
function for translating the ASCII value to Hexadecimal in javascript.window.onload()
function is called on page load so that the function gets executed as soon as the page loads. -
In the
convertASCIItoHex()
function, we pass the ASCII value that needs to be converted.asciiVal.charCodeAt(0)
returns the ASCII code of the input value passed in theconvertASCIItoHex()
function as parameter. The ASCII table contains a mapping to the human-readable letter format and a code associated with them. It looks like the following.DECIMAL HEXCODE Symbol Description 65 41 A Uppercase A 66 42 B Uppercase B 67 43 C Uppercase C 68 44 D Uppercase D 69 45 E Uppercase E 70 46 F Uppercase F 71 47 G Uppercase G 72 48 H Uppercase H 73 49 I Uppercase I 74 4A J Uppercase J The decimal column represents the code for the ASCII value. For instance, the ASCII code for A
is 65. The functionasciiVal.charCodeAt(0)
returns the ASCII value ofasciiVal
which is holding the valueA
. Hence it returns 65. We store the ASCII code in theasciiCode
variable. -
Once we get the ASCII code corresponding to the parameter value, our next step is to convert it into hexadecimal. In the snippet
asciiCode.toString(16)
, the.toString(16)
function returns the hexadecimal value as a string. We store the hexadecimal string value in thehexValue
variable. -
In the final step, we console the hexadecimal equivalent of the passed attribute using the
console.log()
function of JavaScript.
Note
-
It may appear weird to append the
0x
keyword to the converted Hexadecimal value. It is a common approach followed in javascript to identify the number as a hexadecimal value (Refer MSDN Docs for more details). For your business purpose, we can avoid it and follow the hexadecimal value output from the.toString(16)
function. -
The
toString(16)
function is a multipurpose function in javascript. We can use it to convert to different number base systems. We need to pass the decimal base or radix as a parameter to the function. If we look forward to a binary equivalent of the ASCII code, then thetoString(2)
function will return the binary equivalent of the decimal value. The function will typecast the object to a string before returning the binary value. And hence, return type of.toString()
is string. -
The above code considers just one character conversion. Hence if you give a string as input like
convertASCIItoHex("HELLO")
, the function will return the hexadecimal value of the first letter “H”. It is done by the functioncharCode(0)
inasciiVal.charCodeAt(0)
.
Converting a String of ASCII Into Hexadecimal Equivalent in JavaScript
The more common requirements we get in our lives are to convert a string as a whole into the hexadecimal equivalent value rather than a character. The following program takes a string as an input and returns a string of hexadecimal equivalent for each character as output. Each hex value will be separated by ' '
a space for better readability and understanding.
window.onload =
function() {
convertASCIItoHex('Hello!');
convertASCIItoHex('Good Morning World!!');
}
function convertASCIItoHex(asciiString) {
let hex = '';
let tempASCII, tempHex;
asciiString.split('').map(i => {
tempASCII = i.charCodeAt(0)
tempHex = tempASCII.toString(16);
hex = hex + tempHex + ' ';
});
hex = hex.trim();
console.log(hex);
}
Ouput:
48 65 6c 6c 6f 21
47 6f 6f 64 20 4d 6f 72 6e 69 6e 67 20 57 6f 72 6c 64 21 21
Here the convertASCIItoHex()
returns a hexadecimal string value corresponding to the string input provided. It will return a value of type String
. The string of hex codes is separated by spaces for readability and clarity. Let us look at the steps we followed.
-
As discussed in the previous section, we call the
window.onload()
function of javascript and then call theconvertASCIItoHex("Hello!")
function by passing a string"Hello!"
as a parameter to it. -
In the
convertASCIItoHex()
function, we split the input string into characters to make it easy to process them. Hence, at this phase, the"Hello!"
string converts to["H", "e", "l", "l", "o", "!"]
, a string array. -
Next, we apply the ASCII to hex conversion on each element of the array with the
.map()
operator of javascript. It iterates through each element and executes a function on each of them. We pass the function as an inline function or arrow function. -
In the function, we use
charCodeAt(0)
to get the current array element’s ASCII code. Then, on the ASCII code object, we apply thetoString(16)
to convert the ASCII value to a hexadecimal base. Then we push the hexadecimal value to thehex
array, the output array. Note that we use a space between the consecutive conversion for readability sake. You may also prefer using,
or;
separator as demanded by the business needs. -
With
hex = hex + tempHex + ' '
we append a space after each element conversion. Hence, the final result will be having a trailing space. In order to remove that, we use the.trim()
function of javascript. -
Finally, the converted string array is logged into the console with the
console.log(hex)
.
Convert Hexadecimal Back to ASCII
Now, as we have the hexadecimal values ready, the question that arises is how do we confirm that the output is as expected. We achieve the core of the functionality with the fromCharCode(ASCIICode)
function of javascript that returns the ASCII character corresponding to the ASCII code passed in the parameter. Here, we can use the following code.
window.onload = function() {
convertASCIItoHex('48 65 6c 6c 6f 21');
convertASCIItoHex(
'47 6f 6f 64 20 4d 6f 72 6e 69 6e 67 20 57 6f 72 6c 64 21 21');
} function convertHexToASCII(hexString) {
let stringOut = '';
hexString.split(' ').map((i) => {
tempAsciiCode = parseInt(i, 16);
stringOut = stringOut + String.fromCharCode(tempAsciiCode);
});
console.log(stringOut);
}
Output:
Hello!
Good Morning World!!
A couple of methods do the magic here. parseInt(i, 16)
converts an input of base 16
to decimal base. Hence, with this method, we get the ASCII code for the hex value. And the String.fromCharCode(tempAsciiCode)
takes the ASCII code passed as a parameter to this function and returns the ASCII character corresponding to the code.
Remarks
- The most commonly used human-readable form of ASCII includes Alphabets, numbers, and special characters. With the javascript codes, we intend to cover these character sets. We cannot test certain ASCII codes in JavaScript, like the ACK: Acknowledge character, ETX: End of Text character, etc.
- JavaScript string variable can hold a length of maximum 253-1 characters as per ES8 standards. And that amounts to roughly 512MB of data in chrome and around a Gigabyte of data in Firefox. Hence, we can convert longer string values using our code.