2014-02-06 26 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; 
} 

所有最优秀的!

相关问题