Created
January 17, 2019 06:19
-
-
Save Saberko/14a381f0d75a879d25af7a70aacfe20f to your computer and use it in GitHub Desktop.
utf8 byte to unicode 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
/** | |
* utf8 byte to unicode string | |
* @param utf8Bytes | |
* @returns {string} | |
*/ | |
function utf8ByteToUnicodeStr(utf8Bytes){ | |
var unicodeStr =""; | |
for (var pos = 0; pos < utf8Bytes.length;){ | |
var flag= utf8Bytes[pos]; | |
var unicode = 0 ; | |
if ((flag >>>7) === 0 ) { | |
unicodeStr+= String.fromCharCode(utf8Bytes[pos]); | |
pos += 1; | |
} else if ((flag &0xFC) === 0xFC ){ | |
unicode = (utf8Bytes[pos] & 0x3) << 30; | |
unicode |= (utf8Bytes[pos+1] & 0x3F) << 24; | |
unicode |= (utf8Bytes[pos+2] & 0x3F) << 18; | |
unicode |= (utf8Bytes[pos+3] & 0x3F) << 12; | |
unicode |= (utf8Bytes[pos+4] & 0x3F) << 6; | |
unicode |= (utf8Bytes[pos+5] & 0x3F); | |
unicodeStr+= String.fromCharCode(unicode) ; | |
pos += 6; | |
}else if ((flag &0xF8) === 0xF8 ){ | |
unicode = (utf8Bytes[pos] & 0x7) << 24; | |
unicode |= (utf8Bytes[pos+1] & 0x3F) << 18; | |
unicode |= (utf8Bytes[pos+2] & 0x3F) << 12; | |
unicode |= (utf8Bytes[pos+3] & 0x3F) << 6; | |
unicode |= (utf8Bytes[pos+4] & 0x3F); | |
unicodeStr+= String.fromCharCode(unicode) ; | |
pos += 5; | |
} else if ((flag &0xF0) === 0xF0 ){ | |
unicode = (utf8Bytes[pos] & 0xF) << 18; | |
unicode |= (utf8Bytes[pos+1] & 0x3F) << 12; | |
unicode |= (utf8Bytes[pos+2] & 0x3F) << 6; | |
unicode |= (utf8Bytes[pos+3] & 0x3F); | |
unicodeStr+= String.fromCharCode(unicode) ; | |
pos += 4; | |
} else if ((flag &0xE0) === 0xE0 ){ | |
unicode = (utf8Bytes[pos] & 0x1F) << 12;; | |
unicode |= (utf8Bytes[pos+1] & 0x3F) << 6; | |
unicode |= (utf8Bytes[pos+2] & 0x3F); | |
unicodeStr+= String.fromCharCode(unicode) ; | |
pos += 3; | |
} else if ((flag &0xC0) === 0xC0 ){ //110 | |
unicode = (utf8Bytes[pos] & 0x3F) << 6; | |
unicode |= (utf8Bytes[pos+1] & 0x3F); | |
unicodeStr+= String.fromCharCode(unicode) ; | |
pos += 2; | |
} else{ | |
unicodeStr+= String.fromCharCode(utf8Bytes[pos]); | |
pos += 1; | |
} | |
} | |
return unicodeStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment