11
function hex2a(hex) 
{
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}     

This function is not working in chrome, but it is working fine in mozila. can anyone please help.

Thanks in advance

10
  • 2
    Seems to work on Chromium for me : jsfiddle.net/fDzqu Commented Dec 4, 2012 at 7:16
  • 2
    Could you clarify "not working"? What happens when you try it, and how does that differ from what you expect? Do you get any error message? Works fine in Chrome when I try it. jsfiddle.net/Guffa/uT2q5
    – Guffa
    Commented Dec 4, 2012 at 7:24
  • Please give an example input and output. What is it in chrome vs firefix? Commented Dec 4, 2012 at 7:25
  • @Aaradhana: Any errors messages?
    – karthick
    Commented Dec 4, 2012 at 7:25
  • it is displaying Only 'A' in alert, try like this function hex2a(hex) { var str = ''; for (var i = 0; i < hex.length; i += 2) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); return str; } function output() { var text=hex2a(000000000000000000000000000000314d464737); alert('hi'); alert('value'+text); } ​ it is not working:(
    – Aaradhana
    Commented Dec 4, 2012 at 7:32

2 Answers 2

14

From your comments it appears you're calling

hex2a('000000000000000000000000000000314d464737');

and alerting the result.

Your problem is that you're building a string beginning with 0x00. This code is generally used as a string terminator for a null-terminated string.

Remove the 00 at start :

hex2a('314d464737');

You might fix your function like this to skip those null "character" :

function hex2a(hex) {
    var str = '';
    for (var i = 0; i < hex.length; i += 2) {
        var v = parseInt(hex.substr(i, 2), 16);
        if (v) str += String.fromCharCode(v);
    }
    return str;
}  

Note that your string full of 0x00 still might be used in other contexts but Chrome can't alert it. You shouldn't use this kind of strings.

0
0

you need convert every 2 digit of hex '314d464737'.match(/.{1,2}/g) -> [31,4d,46,47,37]

function a2hex(text){
    return [...text].map(x => 
    x.codePointAt()
     .toString(16)
     .padStart(2,"0")
   ).join('')
}
function hex2a(text){
    return String
     .fromCharCode(...text.match(/.{1,2}/g)
     .map(e => 
       parseInt(e, 16))
     )
}

var a = a2hex("hello")
var b = hex2a(a)
console.log(a) // 68656c6c6f
console.log(b) // hello

Not the answer you're looking for? Browse other questions tagged or ask your own question.