2014-10-02 98 views
0

我给出了两个32位整数,其中有一个固定长度的八字符ASCII字符串。从Javascript中的整数中解码固定字符串

例如,字符串“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

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

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>

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

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))

+0

感谢。我喜欢查找方法,尽管对于任何以这种方式编码的通用字符串而言,缓存查找可能不合理。说实话,我很希望有人会给我一个内置于语言中的整洁设施,让我可以用较少的代码完成这项工作,并且最好没有所有的转变以及我的努力所使用的'和'。 – 2014-10-03 11:09:23

+0

为什么你需要这个呢? – exebook 2014-10-03 12:01:41

+0

要将由系统提供的数据以两个32位整数的形式呈现给以8个字符字符串作为输入的接口。无法将第一个系统的输出或输入更改为第二个,因此转换是必要的。 – 2014-10-03 13:57:41

相关问题