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 to hex and summing the numeral part in JavaScript
We are required to write a JavaScript function that takes in a string, converts every character to its hex ASCII value, then sums only the numeric digits (0-9) from the hex representation, ignoring letters (a-f).
Problem
Given a string, we need to:
- Convert each character to its ASCII code
- Convert ASCII codes to hexadecimal
- Extract only numeric digits from the hex strings
- Sum all the numeric digits
Example
Let's see how this works with a complete example:
const str = "Hello, World!";
const toHexAndSum = (str = '') => {
return str
.split('')
.map(c => c.charCodeAt())
.map(n => n.toString(16))
.join('')
.split('')
.filter(c => '0123456789'.includes(c))
.map(d => parseInt(d))
.reduce((a, b) => a + b, 0)
};
console.log(toHexAndSum(str));
91
Step-by-Step Breakdown
Let's trace through the process to understand how it works:
const str = "Hi!";
console.log("Original string:", str);
// Step 1: Split into characters
const chars = str.split('');
console.log("Characters:", chars);
// Step 2: Get ASCII codes
const asciiCodes = chars.map(c => c.charCodeAt());
console.log("ASCII codes:", asciiCodes);
// Step 3: Convert to hex
const hexValues = asciiCodes.map(n => n.toString(16));
console.log("Hex values:", hexValues);
// Step 4: Join and split to get individual hex digits
const hexString = hexValues.join('');
console.log("Joined hex:", hexString);
// Step 5: Filter only numeric digits
const numericDigits = hexString.split('').filter(c => '0123456789'.includes(c));
console.log("Numeric digits:", numericDigits);
// Step 6: Sum the digits
const sum = numericDigits.map(d => parseInt(d)).reduce((a, b) => a + b, 0);
console.log("Sum:", sum);
Original string: Hi! Characters: [ 'H', 'i', '!' ] ASCII codes: [ 72, 105, 33 ] Hex values: [ '48', '69', '21' ] Joined hex: 486921 Numeric digits: [ '4', '8', '6', '9', '2', '1' ] Sum: 30
Alternative Implementation
Here's a more readable version with intermediate steps:
function toHexAndSumReadable(str) {
let hexString = '';
// Convert each character to hex
for (let char of str) {
const ascii = char.charCodeAt(0);
const hex = ascii.toString(16);
hexString += hex;
}
console.log(`Hex representation: ${hexString}`);
// Sum only numeric digits
let sum = 0;
for (let char of hexString) {
if (char >= '0' && char <= '9') {
sum += parseInt(char);
}
}
return sum;
}
console.log(toHexAndSumReadable("ABC"));
Hex representation: 414243 21
Key Points
-
charCodeAt()returns the ASCII value of a character -
toString(16)converts decimal to hexadecimal - Hex digits include 0-9 (numbers) and a-f (letters)
- We only sum the numeric portion (0-9), ignoring hex letters (a-f)
Conclusion
This function demonstrates string-to-hex conversion and selective digit summation. The key insight is filtering only numeric characters from the hex representation before performing the sum operation.
Advertisements
