gpt4 book ai didi

java string.getBytes ("UTF-8") 等效的 javascript

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:25 25 4
gpt4 key购买 nike

我在 java 中有这个字符串:

"test.message"

byte[] bytes = plaintext.getBytes("UTF-8");
//result: [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]

如果我在 javascript 中做同样的事情:

    stringToByteArray: function (str) {         
str = unescape(encodeURIComponent(str));

var bytes = new Array(str.length);
for (var i = 0; i < str.length; ++i)
bytes[i] = str.charCodeAt(i);

return bytes;
},

我得到:

 [7,163,140,72,178,72,244,241,149,43,67,124]

我的印象是 unescape(encodeURIComponent()) 会正确地将字符串转换为 UTF-8。不是这样吗?

引用:

http://ecmanaut.blogspot.be/2006/07/encoding-decoding-utf8-in-javascript.html

最佳答案

您可以使用 TextEncoder,它是 Encoding Living Standard 的一部分.根据Encoding API来自 Chromium 仪表板的条目,它在 Firefox 中发布,并将在 Chrome 38 中发布。还有一个 text-encoding polyfill 可用。

下面的 JavaScript 代码示例返回一个 Uint8Array,其中填充了您期望的值。

var s = "test.message";
var encoder = new TextEncoder();
encoder.encode(s);
// [116, 101, 115, 116, 46, 109, 101, 115, 115, 97, 103, 101]

关于java string.getBytes ("UTF-8") 等效的 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22861828/

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