【问题标题】:Convert array of hex to array to ASCII (Javascript)将十六进制数组转换为 ASCII 数组(Javascript)
【发布时间】:2019-10-31 18:31:42
【问题描述】:

我想将此十六进制数组转换为 ASCII 数组。

我尝试将数组转换为字符串并使用函数将十六进制字符串转换为ASCII,不符合我的期望。

var name = [4d,55,48,41,4d,4d,41,44,20,4e,41,5a,52,45,45,4e,20,42,49,,4e,20,5a,41,49,4e,55,44,49,4e];

name=hex2str(name);

function hex2a(hexx) {
   var hex = hexx.toString();//force conversion
   var str = '';
   for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2)
     str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}

  

预期输出:

name = [M,U,H,A,M,M,A,D, ,N,A,Z,R,E,E,N, ,B,I,N, ,Z,A,I,N,U,D,I,N]

【问题讨论】:

  • 这看起来像 PHP 而不是 JavaScript。

标签: javascript arrays hex ascii


【解决方案1】:

首先4d在javascript中不是有效的十六进制,您需要附加0x前缀以将其标记为十六进制,然后您可以映射数组并执行String.fromCharCode

const name = [0x4d, 0x55, 0x48, 0x41, 0x4d, 0x4d, 0x41, 0x44, 0x20, 0x4e, 0x41, 0x5a, 0x52, 0x45, 0x45, 0x4e, 0x20, 0x42, 0x49, 0x20, 0x4e, 0x20, 0x5a, 0x41, 0x49, 0x4e, 0x55, 0x44, 0x49, 0x4e];

const result = name.map(hex => String.fromCharCode(hex));

console.log(result);

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2022-01-09
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多