在Javascript中解码来自整数的固定字符串

时间:2014-10-02 12:55:49

标签: javascript string integer

我看到两个32位整数,其中包含一个固定长度的八字符ASCII字符串。

例如,字符串" HEYTHERE"分为" HEYT"和" HERE"每个分为四个字节,分别给出0x48455954和0x48455245或1212504404和1212502597。

在Javascript中将这两个数字转换回字符串的最有效方法是什么?

到目前为止,我有以下内容,但我想知道是否有更快/更少笨拙的方式:

let xx1 = [ 1212504404, 1212502597 ];
let xx1str = String.fromCharCode((xx1[0] >> 24) & 255) +
    String.fromCharCode((xx1[0] >> 16) & 255) +
    String.fromCharCode((xx1[0] >> 8)  & 255) +
    String.fromCharCode( xx1[0]        & 255) +
    String.fromCharCode((xx1[1] >> 24) & 255) +
    String.fromCharCode((xx1[1] >> 32) & 255) +
    String.fromCharCode((xx1[1] >> 8)  & 255) +
    String.fromCharCode( xx1[1]        & 255); 

1 个答案:

答案 0 :(得分:1)

我认为你可以有一个包含两个字符或四个字符的哈希表。



hash2 = { '4040': 'AA', '4041': 'AB',
         '4845':'HE',
         '5954':'YT',
         '4845':'HE',
         '5245':'RE'
        }
function madDecode(num) {
  return hash2[num.toString(16).substr(0, 4)] 
  + hash2[num.toString(16).substr(4, 4)]

}
out.innerHTML = madDecode(0x40404041) +', '
  + madDecode(1212504404) + madDecode(1212502597)

<span id=out></span>
&#13;
&#13;
&#13;

您可以使用4个字符哈希进一步改进。甚至进一步使用数组而不是对象。

&#13;
&#13;
hash2 = []

function chCode(x) {
  x = x.toString(16)
  while (x.length < 2) x = '0' + x
  return x
}

function makeHash() {
  for (var i = 32; i < 128; i++) {
    for (var j = 32; j < 128; j++) {
      hash2[parseInt(chCode(i) + chCode(j), 16)] = String.fromCharCode(i, j)
    }
  }
}

function arrDecode(num) {
  var na = (num & 0xffff0000) >> 16,
    nb = num & 0xffff
  return hash2[na] + hash2[nb]
}

makeHash()
document.write(arrDecode(1212504404) + arrDecode(1212502597))
&#13;
&#13;
&#13;