I need to translate ASCII code in HEX to characters. I got from server numbers(as string) in ascii, like: 64656661756c74 (which means 'default'). I know about String.fromCharCode(), but first i need to split the raw message to 2-digits pieces(array). How can i split 2-digits-duration based? Thanks.
4 Answers
Since the string is hex string representation, you have also to convert in decimal number before you pass to String.fromCharCode:
const str = "64656661756c74"
.match(/.{2}/g)
.map(ch => String.fromCharCode(parseInt(ch, 16)))
.join("");
console.log(str);
// "default"
That basically store in str the value "default", as you said.
1 Comment
iPirat
Nice solution. .
Using replace:
let a = '64656661756c74';
let r = a.replace(/([0-9a-f]{2})/g, (m, a) => String.fromCharCode(parseInt(a, 16)))
console.log(r)
Oldschool approach:
let a = '64656661756c74', r = '';
for (let i = 0; i < a.length; i+=2)
r += String.fromCharCode(parseInt(a.substring(i, i+2), 16))
console.log(r)
Comments
As noted in comments above, your ASCII sequence is probably incorrect. Maybe it is a hexadecimal stream.
Assuming the correct ASCII numbers, you can go as following,
var str = '68697065857684';
str = str.match(/.{1,2}/g);
for (index = str.length - 1; index >= 0; --index) {
var temp = str[index];
str[index]= String.fromCharCode(temp);
}
console.log(str);
3 Comments
Bergi
Yes, it's hex (decimal doesn't make sense), and it's lowercase!
Abdullah Leghari
You are right @Bergi I've seen a text stream in hex for the first time though :)
Alex
Sorry, I updated my question, yes, its ASCII in hex. The server that returns such an answers is 'Grass valley K2 summit'. Its AMP control protocol.
68 69 70 65 85 76 84.fromCharCode; Or rely on the ASCII encoding for that block being the same as the ASCII codepoints and the Unicode codespoints and usefromCodePoint. IMO, that's worthy of a code comment.