UTF-8 ArrayBuffer和String之间的转换 [英] Conversion between UTF-8 ArrayBuffer and String

查看:3629
本文介绍了UTF-8 ArrayBuffer和String之间的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayBuffer ,其中包含使用UTF-8编码的字符串,我无法找到转换此类 ArrayBuffer的标准方法到JS String (据我所知,它是用UTF-16编码的)。

I have an ArrayBuffer which contains a string encoded using UTF-8 and I can't find a standard way of converting such ArrayBuffer into a JS String (which I understand is encoded using UTF-16).

I我已经在很多地方看到过这段代码,但我看不出它如何适用于长度超过1个字节的任何UTF-8代码点。

I've seen this code in numerous places, but I fail to see how it would work with any UTF-8 code points that are longer than 1 byte.

return String.fromCharCode.apply(null, new Uint8Array(data));

同样,我找不到从字符串转换的标准方式到UTF-8编码 ArrayBuffer

Similarly, I can't find a standard way of converting from a String to a UTF-8 encoded ArrayBuffer.

推荐答案

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}

在互联网的帮助下,我已经完成了这些小功能,他们应该解决你的问题!这是工作JSFiddle

I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.

编辑

由于Uint8Array的来源是外部的,你不能使用 atob 你只需要删除它(工作小提琴):

Since the source of the Uint8Array is external and you can't use atob you just need to remove it(working fiddle):

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;
}

这篇关于UTF-8 ArrayBuffer和String之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆