2014-10-02 95 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

相關問題