Last active
July 7, 2019 14:51
-
-
Save janelin612/464328333f11b9332a3dbadf38c3dfc6 to your computer and use it in GitHub Desktop.
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 decode(text) { | |
if (!text) | |
return ""; | |
//string to byte[] | |
let byteArr = []; | |
for (let i = 0; i < text.length; i++) { | |
byteArr.push(text.charCodeAt(i)); | |
} | |
let str = ""; | |
for (let i = 0; i < byteArr.length;) { | |
let binary = byteArr[i].toString(2); | |
let head = binary.match(/^1+?(?=0)/); | |
if (head && binary.length == 8) { | |
//該字元需要幾個位元組 | |
let bytesLength = head[0].length; | |
//第一個位元組的實際資料區 | |
let body = binary.slice(bytesLength); | |
for (let j = 1; j < bytesLength; j++) { | |
//組合資料 | |
body += byteArr[i + j].toString(2).slice(2); | |
} | |
str += String.fromCharCode(parseInt(body, 2)); | |
i += bytesLength; | |
} else { | |
str += String.fromCharCode(byteArr[i]); | |
i++; | |
} | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment