Created
August 13, 2013 11:50
-
-
Save alxgsv/6220357 to your computer and use it in GitHub Desktop.
Convert bytes list to utf-8 string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function bytes2string(bytes) { | |
var ix = 0; | |
if( bytes.slice(0,3) == [239, 187, 191]) { | |
ix = 3; | |
} | |
var string = ""; | |
for( ; ix < bytes.length; ix++ ) { | |
var byte1 = bytes[ix]; | |
if( byte1 < 0x80 ) { | |
string += String.fromCharCode(byte1); | |
} else if( byte1 >= 0xC2 && byte1 < 0xE0 ) { | |
var byte2 = bytes[++ix]; | |
string += String.fromCharCode(((byte1&0x1F)<<6) + (byte2&0x3F)); | |
} else if( byte1 >= 0xE0 && byte1 < 0xF0 ) { | |
var byte2 = bytes[++ix]; | |
var byte3 = bytes[++ix]; | |
string += String.fromCharCode(((byte1&0xFF)<<12) + ((byte2&0x3F)<<6) + (byte3&0x3F)); | |
} else if( byte1 >= 0xF0 && byte1 < 0xF5) { | |
var byte2 = bytes[++ix]; | |
var byte3 = bytes[++ix]; | |
var byte4 = bytes[++ix]; | |
var codepoint = ((byte1&0x07)<<18) + ((byte2&0x3F)<<12)+ ((byte3&0x3F)<<6) + (byte4&0x3F); | |
codepoint -= 0x10000; | |
string += String.fromCharCode( | |
(codepoint>>10) + 0xD800, | |
(codepoint&0x3FF) + 0xDC00 | |
); | |
} | |
} | |
return string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment