gpt4 book ai didi

javascript - 将 FileReader.readAsBinaryString 转换为 Unicode 转义字符串

转载 作者:行者123 更新时间:2023-11-30 07:14:47 25 4
gpt4 key购买 nike

文件读取器。 readAsBinaryString()返回 UTF-8 编码的二进制字符串。我如何才能获取作为一系列 Unicode 转义序列 (\uxxxx) 的数据?

最佳答案

FileReader.readAsBinaryString() 已弃用 - 改为使用 readAsArrayBuffer() .这允许您使用以下两种方法之一将输入字符串转换为转义的 unicode 字符:

方法一

这使用了 ArrayBuffer 和一个 Uint8Array View 。在下面的演示中,假设缓冲区已预加载(而是提供了一些虚拟数据)。

var buffer = new Uint8Array([0x20, 0xac, 0x2b, 0x08]),  // big-endian format
pos = 0, txt = "";

// iterate buffer byte-per-byte and build string:
while(pos < buffer.length)
txt += "\\u" + toString(buffer[pos++]) + toString(buffer[pos++]);

// make sure we end up with two digits (v < 0x10)
function toString(v) {
var s = v.toString(16); return s.length === 1 ? "0" + s : s
}

out.innerHTML = txt;
<output id="out"></output>

如果数据是小端(在大多数主流系统上),您可以在这里使用 Uint16Array,并且只需将单个值转换为字符串而不是两个。或者使用 DataView 以便您可以阅读请求字节顺序。这可能会或可能不会稍微快一些(浏览器将进行字节交换,我们在一次操作中读取 16 位,但检查只是在 toString 方法中合并):

var data = new Uint8Array([0x20, 0xac, 0x2b, 0x08]),  // big-endian format
view = new DataView(data.buffer), // use a view on the ArrayBuffer
pos = 0, txt = "";

// iterate buffer byte-per-byte and build string:
while(pos < view.byteLength) {
txt += "\\u" + toString(view.getUint16(pos, false)); // true = little endian
pos += 2
};

// make sure we end up with four digits
function toString(v) {
var s = v.toString(16);
return s.length === 3 ? "0" + s : (s.length === 2 ? "00" + s : s)
}

out.innerHTML = txt;
<output id="out"></output>

方法二

这使用新的 TextDecoder API 来解析输入缓冲区 - 这里也假定为 ArrayBuffer。

然后 escape 与替换一起使用。这是一种快速的转换方式,但是 escape() 也被弃用了。然而,它不会很快消失,所以如果你觉得大胆,它可能是一个选择——无论如何我都会把它包括在这里:

var td = new TextDecoder("utf-16be"),                   // be = big endian, def: le
buffer = new Uint8Array([0x20, 0xac, 0x2b, 0x08]); // big-endian format

// assumes data loaded into an ArrayBuffer
var txt = td.decode(buffer);

// escape is deprecated but won't go anywhere for a while:
out.innerHTML = escape(txt).replace(/%/g, "\\");

// or use the same last step as in method 1, just showing an alternative way

//=> "\u20AC\u2B08"
<output id="out"></output>

注意:您可能已经注意到我为字节顺序指定了大端。通常,在从网络读取文件或二进制数据时使用大端(又名网络顺序)。如果数据恰好是小端格式,则需要交换字节顺序:

对于方法 1,您可以:

while(pos < buffer.length) {
txt += "\\u" + toString(buffer[pos+1]) + toString(buffer[pos]);
pos += 2;
}

或者只是使用 Uint16Array 和上面提到的修改后的 toString 方法。

对于方法 2,您可以简单地为 utf-16 指定小端版本:

var td = new TextDecoder("utf-16");  // default = little-endian

请注意,TextDecoder 尚未稳定 nor supported in all browsers .

关于javascript - 将 FileReader.readAsBinaryString 转换为 Unicode 转义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29007389/

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