【问题标题】:JavaScript equivalent of Java's String.getBytes(StandardCharsets.UTF_8)JavaScript 等效于 Java 的 String.getBytes(StandardCharsets.UTF_8)
【发布时间】:2021-10-25 15:16:41
【问题描述】:

我有以下 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 equivalent

但它给出的结果与上面相同。

还有什么我可以在这里尝试的,以便让 JavaScript 生成与 Java 相同的数组吗?

【问题讨论】:

  • 区别似乎是有符号字节与无符号字节。只需用new Int8Array() 包装结果即可。

标签: javascript java character-encoding graalvm graaljs


【解决方案1】:

就字节而言,结果是相同的,JS 只是默认为 unsigned 字节。 U in Uint8Array 代表“未签名”;签名的变体称为Int8Array

转换很简单:只需将结果传递给Int8Array 构造函数:

console.log(new Int8Array(new TextEncoder().encode("\u00a0"))); // Int8Array [ -62, -96 ]

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2021-04-26
    • 2010-11-29
    • 2011-06-23
    • 1970-01-01
    • 2014-06-12
    • 2018-05-30
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多