2014-02-06 48 views
3

在Java中,如果我們知道一個字節數組的編碼,我們可以對其進行解碼,並得到相應的字符如下 -的JavaScript等同於Java的字符集/ String類組合解碼字節數組

Charset charset = Charset.forName(encoding); 
String decodedString = new String(byteArray, charset); 

哪有在JavaScript中實現相同的結果?

假設我讀了一個我知道的文件是windows-1253編碼(希臘文)。爲了正確顯示文件內容,我必須解碼文件中的字節。

如果我們不進行解碼(或打開的,不知道編碼的文本編輯器文件),我們可能會看到這樣的事情 -

ÁõôÞ åßíáé ç åëëçíéêÞ. 

但是,當這個文本(即字節)被解碼,我們得到

Αυτή είναι η ελληνική. 
+0

不幸的是,不幸的是。節點還是瀏覽器? – SLaks

+0

@SLaks,瀏覽器。 – Wes

+0

你能給我們一個你想要從/轉換的字符集的例子嗎?你使用它的想法涉及到什麼? – crush

回答

0

在JavaScript中字符串總是UTF-16編碼。 ECMAScript

0

希望這將幫助你:

var getString = function (strBytes) { 

    var MAX_SIZE = 0x4000; 
    var codeUnits = []; 
    var highSurrogate; 
    var lowSurrogate; 
    var index = -1; 

    var result = ''; 

    while (++index < strBytes.length) { 
     var codePoint = Number(strBytes[index]); 

    if (codePoint === (codePoint & 0x7F)) { 


    } else if (0xF0 === (codePoint & 0xF0)) { 
     codePoint ^= 0xF0; 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
    } else if (0xE0 === (codePoint & 0xE0)) { 
     codePoint ^= 0xE0; 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
    } else if (0xC0 === (codePoint & 0xC0)) { 
     codePoint ^= 0xC0; 
     codePoint = (codePoint << 6) | (strBytes[++index]^0x80); 
    } 

     if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) != codePoint) 
      throw RangeError('Invalid code point: ' + codePoint); 

     if (codePoint <= 0xFFFF) 
      codeUnits.push(codePoint); 
     else { 
      codePoint -= 0x10000; 
      highSurrogate = (codePoint >> 10) | 0xD800; 
      lowSurrogate = (codePoint % 0x400) | 0xDC00; 
      codeUnits.push(highSurrogate, lowSurrogate); 
     } 
     if (index + 1 == strBytes.length || codeUnits.length > MAX_SIZE) { 
      result += String.fromCharCode.apply(null, codeUnits); 
      codeUnits.length = 0; 
     } 
    } 

    return result; 
} 

所有最優秀的!

相關問題