javascript javascript中的十六进制转字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13697829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hexadecimal to string in javascript
提问by Aaradhana
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.
此功能在 chrome 中不起作用,但在 mozila 中运行良好。任何人都可以帮忙。
Thanks in advance
提前致谢
回答by Denys Séguret
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.
您的问题是您正在构建一个以 0x00 开头的字符串。此代码通常用作以空字符结尾的字符串的字符串终止符。
Remove the 00
at start :
删除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.
请注意,您的充满 0x00 的字符串仍可能在其他上下文中使用,但 Chrome 无法提醒它。你不应该使用这种字符串。