Javascript character (ASCII) to Hex
Categories:
Converting JavaScript Characters (ASCII) to Hexadecimal

Learn how to convert individual characters or entire strings to their hexadecimal representations in JavaScript, covering common use cases and methods.
Converting characters to their hexadecimal equivalents is a common task in web development, especially when dealing with data serialization, URL encoding, or cryptographic operations. In JavaScript, characters are typically represented using Unicode, but for many purposes, their ASCII or UTF-8 hexadecimal values are required. This article will guide you through various methods to achieve this conversion, from simple character-to-hex to full string transformations.
Understanding Character Encoding Basics
Before diving into code, it's important to understand what we're converting. Each character on your computer is represented by a numerical value. ASCII (American Standard Code for Information Interchange) assigns unique numbers to 128 characters, primarily English letters, numbers, and symbols. Unicode, on the other hand, is a much broader standard that encompasses almost all the world's writing systems, with UTF-8 being its most common encoding. When we talk about converting a character to hex in JavaScript, we're usually referring to its Unicode code point, which often aligns with its ASCII value for basic characters.
flowchart TD A[Character Input] --> B{"Get Code Point"} B --> C["String.prototype.charCodeAt()"] C --> D["Convert to Hexadecimal"] D --> E["Number.prototype.toString(16)"] E --> F[Hexadecimal Output]
Process of converting a character to its hexadecimal representation.
Method 1: Converting a Single Character to Hex
The most straightforward way to convert a single character to its hexadecimal representation in JavaScript is by using the charCodeAt()
method, followed by toString(16)
. The charCodeAt()
method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. For most common ASCII characters, this will be their ASCII value. The toString(16)
method then converts this integer into its hexadecimal string representation.
function charToHex(char) {
if (char.length !== 1) {
throw new Error("Input must be a single character.");
}
const codePoint = char.charCodeAt(0);
return codePoint.toString(16).toUpperCase();
}
console.log(charToHex('A')); // Output: 41
console.log(charToHex('a')); // Output: 61
console.log(charToHex('!')); // Output: 21
console.log(charToHex('€')); // Output: 20AC (UTF-16 code unit for Euro sign)
JavaScript function to convert a single character to its hexadecimal value.
charCodeAt()
might return a surrogate pair. For full Unicode code points, use codePointAt()
instead, which returns the actual Unicode code point, allowing for correct handling of emojis and other extended characters.Method 2: Converting an Entire String to Hexadecimal
To convert an entire string, you can iterate over each character in the string, apply the charToHex
logic, and concatenate the results. This approach effectively converts each character's code point into its hexadecimal representation and joins them together.
function stringToHex(str) {
let hexString = '';
for (let i = 0; i < str.length; i++) {
const codePoint = str.charCodeAt(i);
// Pad with a leading zero if the hex value is a single digit
hexString += ('0' + codePoint.toString(16)).slice(-2).toUpperCase();
}
return hexString;
}
console.log(stringToHex('Hello')); // Output: 48656C6C6F
console.log(stringToHex('JS!')); // Output: 4A5321
JavaScript function to convert an entire string to its hexadecimal representation.
('0' + codePoint.toString(16)).slice(-2)
part ensures that each hexadecimal character representation is always two digits long (e.g., 'A' becomes '41', not '4'). This is crucial for consistent parsing later.Handling UTF-8 Hexadecimal Conversion
The methods above primarily deal with UTF-16 code units. If you need to convert a string to its UTF-8 hexadecimal byte sequence, the process is slightly more involved as UTF-8 uses variable-width encoding. This typically requires encoding the string into a Uint8Array
first, then converting each byte to hex.
function stringToUtf8Hex(str) {
const encoder = new TextEncoder();
const utf8Bytes = encoder.encode(str);
let hexString = '';
for (const byte of utf8Bytes) {
hexString += ('0' + byte.toString(16)).slice(-2).toUpperCase();
}
return hexString;
}
console.log(stringToUtf8Hex('Hello')); // Output: 48656C6C6F (same as ASCII for these chars)
console.log(stringToUtf8Hex('€')); // Output: E282AC (UTF-8 representation of Euro sign)
console.log(stringToUtf8Hex('你好')); // Output: E4BDA0E5A5BD (UTF-8 for 'ni hao')
JavaScript function to convert a string to its UTF-8 hexadecimal byte sequence.
charCodeAt()
) and UTF-8 byte sequences. For web protocols like URL encoding or when interacting with systems expecting specific byte encodings, UTF-8 conversion is often necessary.