gpt4 book ai didi

javascript 将 readAsBinaryString 的结果转换为 utf8

转载 作者:行者123 更新时间:2023-11-28 08:10:26 32 4
gpt4 key购买 nike

我有一个以下格式的文件:

utf-8 encoded text block
separator
binary data block

我使用 JavaScript 的 FileReader 使用

将文件作为二进制字符串读取

FileReader.readAsBinaryString 像这样:

var reader = new FileReader();

reader.onload = function(evt){
// Here I use the separator position to divide the file content into
// header and binary
...
console.log(header);

};
FileReader.onerror = function (evt) {
onFailure(evt.target.error.code);
}

reader.readAsBinaryString(blobFile);

header 未解析为 UTF-8。我知道 FileReader.readAsText 会考虑文件的编码,而 FileReader.readAsBinaryString 会逐字节读取文件。

如何将 header 转换为 utf8?读取文件两次,一次作为二进制字符串读取二进制数据,再次作为文本获取 utf8 编码的第一个 block ,这对我来说没有吸引力。

最佳答案

我在 http://snipplr.com/view/31206/ 上找到了答案:我已经在法语字符上对其进行了测试,然后它会毫无问题地转换为 utf8。

function readUTF8String(bytes) {
var ix = 0;

if (bytes.slice(0, 3) == "\xEF\xBB\xBF") {
ix = 3;
}

var string = "";
for (; ix < bytes.length; ix++) {
var byte1 = bytes[ix].charCodeAt(0);
if (byte1 < 0x80) {
string += String.fromCharCode(byte1);
} else if (byte1 >= 0xC2 && byte1 < 0xE0) {
var byte2 = bytes[++ix].charCodeAt(0);
string += String.fromCharCode(((byte1 & 0x1F) << 6) + (byte2 & 0x3F));
} else if (byte1 >= 0xE0 && byte1 < 0xF0) {
var byte2 = bytes[++ix].charCodeAt(0);
var byte3 = bytes[++ix].charCodeAt(0);
string += String.fromCharCode(((byte1 & 0xFF) << 12) + ((byte2 & 0x3F) << 6) + (byte3 & 0x3F));
} else if (byte1 >= 0xF0 && byte1 < 0xF5) {
var byte2 = bytes[++ix].charCodeAt(0);
var byte3 = bytes[++ix].charCodeAt(0);
var byte4 = bytes[++ix].charCodeAt(0);
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;
}

关于javascript 将 readAsBinaryString 的结果转换为 utf8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24282294/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com