[英]JavaScript equivalent of Java's String.getBytes(StandardCharsets.UTF_8)
我有以下 Java 代码:
String str = "\u00A0";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
System.out.println(Arrays.toString(bytes));
这将输出以下字节数组:
[-62, -96]
我试图在 Javascript 中获得相同的结果。 我已经尝试了这里发布的解决方案:
https://stackoverflow.com/a/51904484/12177456
function strToUtf8Bytes(str) {
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) {
let charCode = str.charCodeAt(ii);
if (charCode < 0x80) utf8.push(charCode);
else if (charCode < 0x800) {
utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
} else if (charCode < 0xd800 || charCode >= 0xe000) {
utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
} else {
ii++;
// Surrogate pair:
// UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
// splitting the 20 bits of 0x0-0xFFFFF into two halves
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0 | (charCode >> 18),
0x80 | ((charCode >> 12) & 0x3f),
0x80 | ((charCode >> 6) & 0x3f),
0x80 | (charCode & 0x3f),
);
}
}
return utf8;
}
console.log(strToUtf8Bytes("h\u00A0i"));
但这给出了这个(这是一个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array ):
[194, 160]
这对我来说是个问题,因为我正在使用 graal js 引擎,并且需要将数组传递给需要byte[]
的 java 函数,因此数组中的任何值 > 127 都会导致错误,如下所述:
https://github.com/oracle/graal/issues/2118
注意我还尝试了TextEncoder
类而不是strToUtf8Bytes
函数,如下所述:
java string.getBytes("UTF-8") javascript 等价物
但它给出了与上面相同的结果。
还有什么我可以在这里尝试的,以便我可以让 JavaScript 生成与 Java 相同的数组?
结果在字节方面是相同的,JS 只是默认为无符号字节。 Uint8Array
U
代表“无符号”; 签名变体称为Int8Array
。
转换很简单:只需将结果传递给Int8Array
构造函数:
console.log(new Int8Array(new TextEncoder().encode("\ "))); // Int8Array [ -62, -96 ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.