我有以下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引擎,并且需要将数组传递给一个需要byte[]
的java函数,因此数组中的任何值> 127都会导致一个错误,如下所述:
https://github.com/oracle/graal/issues/2118
注意,我还尝试了TextEncoder
类而不是strToUtf8Bytes
函数,如下所述:
java string.getBytes("UTF-8") javascript equivalent
但是它给出了与上面相同的结果。
这里还有什么可以尝试的吗?这样我就可以让JavaScript生成与Java相同的数组了吗?
发布于 2021-10-25 15:36:57
结果在字节方面是相同的,JS只是默认为无符号字节。U
在Uint8Array
中代表“无符号”;有符号的变体称为Int8Array
。
转换很简单:只需将结果传递给Int8Array
构造函数:
console.log(new Int8Array(new TextEncoder().encode("\u00a0"))); // Int8Array [ -62, -96 ]
https://stackoverflow.com/questions/69710627
复制相似问题