Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Converting ASCII to hexadecimal in JavaScript
Converting ASCII characters to hexadecimal is a common task in JavaScript. Each character has an ASCII code that can be represented as a hexadecimal value.
Understanding ASCII to Hex Conversion
Each character in a string has an ASCII code. For example, '1' has ASCII code 49, '5' has 53, and '9' has 57. Converting to hexadecimal: 49 ? 31, 53 ? 35, 57 ? 39.
Example
Here's how to convert ASCII characters to their hexadecimal representation:
const str = '159';
const convertToHexa = (str = '') => {
const res = [];
const { length: len } = str;
for (let n = 0, l = len; n < l; n++) {
const hex = Number(str.charCodeAt(n)).toString(16);
res.push(hex);
}
return res.join('');
}
console.log(convertToHexa('159'));
console.log(convertToHexa('ABC'));
console.log(convertToHexa('Hello'));
313539 414243 48656c6c6f
Step-by-Step Breakdown
Let's understand how the conversion works:
const char = '1';
const asciiCode = char.charCodeAt(0);
const hexValue = asciiCode.toString(16);
console.log(`Character: ${char}`);
console.log(`ASCII Code: ${asciiCode}`);
console.log(`Hex Value: ${hexValue}`);
Character: 1 ASCII Code: 49 Hex Value: 31
Alternative Approach Using Map
A more functional approach using the map() method:
const convertToHexMap = (str = '') => {
return str.split('').map(char => char.charCodeAt(0).toString(16)).join('');
}
console.log(convertToHexMap('159'));
console.log(convertToHexMap('Test'));
313539 54657374
Comparison
| Method | Readability | Performance |
|---|---|---|
| For Loop | Good | Faster for large strings |
| Map Method | Excellent | Good for small strings |
Conclusion
Both methods effectively convert ASCII characters to hexadecimal. Use the for loop approach for better performance with large strings, or the map method for cleaner, more readable code.
Advertisements
