簡體   English   中英

將170位二進制字符串轉換為較短的格式,然后再次返回(Javascript)

[英]Convert 170 Digit Binary String Into Shorter Format and Back Again (Javascript)

我在這里做了一些益智模擬。

170個單元的開/關狀態(用戶看不見的一些狀態)存儲在一個數組中,為了能夠重新創建特定的配置,我在頁面底部顯示了數組的內容,然后可以將其放入作為URL參數輸入,以在頁面加載時“設置”特定配置

我的問題是數組的輸出是一個170位二進制數,這很麻煩!

我嘗試使用

parseInt(input,2).toString(30)

parseInt(input,30).toString(2)

作為將這個170位二進制數字簡單轉換為更細的字母數字格式(然后再次返回以供我的“設置”初始化程序讀取)的一種方法,但是據我所知,我要處理的數字太大而無法適合那種功能。

我的下一個想法是,我可以將170位數字拆分為一些可以被函數消化的部分,但是當我確定這種轉換一定很常見並且有人會能夠使我直截了當地了解“正確”的解決方法。

提前致謝!

您的想法是正確的,只是JavaScript無法准確表示那么大的數字。 當您使用parseInt將其轉換為JavaScript數字時,您的170位數字將失去准確性。 它不能一點一點地代表原始數字。

解決方案很簡單:滾動您自己的數字解析功能,以較小的塊處理170位數字。

function encode(a) {
    var b = "";
    while (a.length > 0) {
        b = parseInt(a.slice(-5), 2).toString(32) + b;
        a = a.slice(0, -5);
    }
    return b;
}

function decode(a) {
    var b = "";
    while (a.length > 0) {
        b = ("00000" + parseInt(a.slice(-1), 32).toString(2)).slice(-5) + b;
        a = a.slice(0, -1);
    }
    return b;
}

var s = "00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000";
var e = encode(s); // "000lq2k8et1a45es002748kh2i4a0tp000"
var d = decode(e); // d === s

更一般的功能:

function convert(string, base1, base2) {
    var result = "",
        chunkw = 0,  // number of characters to write per chunk
        chunkr = 0,  // number of characters to read per chunk
        padstr = "", // string of zeros for padding the write chunks
        slice;
    while (Math.pow(2, chunkw) < base1) chunkw += 1;
    while (Math.pow(2, chunkr) < base2) chunkr += 1;
    while (padstr.length < chunkw) padstr += "0";
    while (string.length > 0) {
        slice = string.slice(-chunkr);
        slice = parseInt(slice, base1).toString(base2);
        slice = (padstr + slice).slice(-chunkw);
        result = slice + result;
        string = string.slice(0, -chunkr);
    }
    return result;
}
var x = "00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000";
var a = convert(x, 2, 32);
var b = convert(a, 32, 2);
console.log(x + "\n" + a + "\n" + b);
//       00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000
//       000lq2k8et1a45es002748kh2i4a0tp000
//       00000000000000010101110100001010100010000111011101000010101000100001010111011100000000000000010001110010001000101001000100010100100010001010000001110111001000000000000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM