简体   繁体   English

将Uint8Array转换为javascript中的字符串(带有中文字符)

[英]Convert Uint8Array to string in javascript (with Chinese characters)

I am using the following code to convert a Uint8Array object to string: 我正在使用以下代码将Uint8Array对象转换为字符串:

var fileData = cc.FileUtils.getInstance().getByteArrayFromFile("file.txt");

// fileData is a Uint8Array object
var dataString = "";
for(i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
}
alert(dataString);

and if the content of the "file.txt" is latin characters say 如果“ file.txt”的内容是拉丁字符,请说

"this is a watch" “这是一块手表”

then the codes above works fine. 那么上面的代码可以正常工作。

But, if there is non latin characters in the file say "thank you 谢谢" 但是,如果文件中包含非拉丁字符,请说“谢谢”

then the convert result is not correct. 则转换结果不正确。

Hope someone can help me, thanks :) 希望有人可以帮助我,谢谢:)

Not the solution, but to find the problem please verify the array by getting the character codes like this 不是解决方案,但是要找到问题,请通过获取类似这样的字符代码来验证数组

var str= "thank you 谢谢";
for(i = 0; i < str.length; i++) {
    console.log(str.charCodeAt(i));
}

EDIT: 编辑:

As it is giving 34 for 35874 it is clear that the character code is not coming in 16 bits. 由于给35874提供了34 ,因此很明显字符代码不是以16位出现的。 Because 因为

35874 = 10001100 00100010 => in 8 bits => 00100010 = 34 35874 = 10001100 00100010 => 8位=> 00100010 = 34

Please check the encoding of the file. 请检查文件的编码。 Also see whether you can specify the encoding in getByteArrayFromFile . 另请参阅是否可以在getByteArrayFromFile指定编码。 Usually a charset is used to read multiple bytes as you can see in this as an example - actionscript function 如示例所示,通常使用字符集读取多个字节-actionscript函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM