Table of Contents
- Converting a Single ASCII Character to Hexadecimal
- Converting an ASCII String to Hexadecimal
- Converting Hexadecimal to ASCII
- Error Handling and Optimization
Converting a Single ASCII Character to Hexadecimal
JavaScript offers a straightforward way to convert a single ASCII character to its hexadecimal representation. The charCodeAt()
method retrieves the character’s decimal ASCII value, which is then easily converted to hexadecimal using toString(16)
.
function asciiToHex(asciiChar) {
if (typeof asciiChar !== 'string' || asciiChar.length !== 1) {
throw new Error("Input must be a single ASCII character.");
}
let hex = asciiChar.charCodeAt(0).toString(16);
return hex.padStart(2, '0');
}
console.log(asciiToHex('A')); // Output: 41
console.log(asciiToHex(' ')); // Output: 20
console.log(asciiToHex('!')); // Output: 21
The padStart(2, '0')
method ensures that single-digit hexadecimal values (0-F) are represented with a leading zero for consistency (e.g., “0A” instead of “A”).
Converting an ASCII String to Hexadecimal
To convert an entire ASCII string, we iterate through each character and apply the asciiToHex
function.
function stringAsciiToHex(asciiString) {
if (typeof asciiString !== 'string') {
throw new Error("Input must be a string.");
}
let hexString = "";
for (let i = 0; i < asciiString.length; i++) {
hexString += asciiToHex(asciiString[i]);
}
return hexString;
}
console.log(stringAsciiToHex("Hello")); // Output: 48656c6c6f
console.log(stringAsciiToHex("JavaScript")); // Output: 4a617661536372697074
Converting Hexadecimal to ASCII
The reverse conversion—from hexadecimal to ASCII—involves parsing the hexadecimal string, converting each two-digit hexadecimal segment to its decimal equivalent, and then using String.fromCharCode()
to reconstruct the ASCII character.
function hexToAscii(hexString) {
if (typeof hexString !== 'string' || hexString.length % 2 !== 0) {
throw new Error("Input must be a valid hexadecimal string.");
}
let asciiString = "";
for (let i = 0; i < hexString.length; i += 2) {
const hexPair = hexString.substring(i, i + 2);
const decimalValue = parseInt(hexPair, 16);
asciiString += String.fromCharCode(decimalValue);
}
return asciiString;
}
console.log(hexToAscii("48656c6c6f")); // Output: Hello
console.log(hexToAscii("4a617661536372697074")); // Output: JavaScript
Error Handling and Optimization
The provided functions include basic error handling to check for invalid input types and lengths. For production environments, more comprehensive error handling might be necessary to gracefully manage unexpected input. For extremely large strings, consider using more performant methods like typed arrays for improved efficiency. These examples provide a solid foundation for ASCII-hexadecimal conversions in JavaScript.