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

查看:61
本文介绍了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).

我在很多地方都看到过这段代码,但我看不出它如何处理任何长度超过 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));

同样,我找不到从 String 转换为 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;
}

警告:escape 和 unescape 已从网络标准中删除. 看这个.

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

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