Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal to string in javascript

Tags:

javascript

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

like image 509
Aaradhana Avatar asked Dec 04 '12 07:12

Aaradhana


People also ask

How do you use hexadecimal in JavaScript?

Uses of Hexadecimal Numbers in JavaScriptJavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.

How do you convert hexadecimal to decimal?

Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers.


1 Answers

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.

like image 178
Denys Séguret Avatar answered Sep 20 '22 22:09

Denys Séguret