代码之家  ›  专栏  ›  技术社区  ›  Kevin Cruijssen

UTF-8字符串到序号值:Python输出的Java等价物

  •  2
  • Kevin Cruijssen  · 技术社区  · 7 年前

    "Aä$$€h" . 它包含三个不同的普通ASCII字符( A$h ),和两个非ASCII字符( ä€

    # coding: utf-8
    input = u'Aä$$€h'
    print [ord(c) for c in input.encode('utf-8')]
    # Grouped per character:
    print [[ord(x) for x in c.encode('utf-8')] for c in input_code]
    

    [65, 195, 164, 36, 36, 226, 130, 172, 104]
    [[65], [195, 164], [36], [36], [226, 130, 172], [104]]
    

    Try it online.

    String input = "Aä$$€h";
    byte[] byteArray = input.getBytes(java.nio.charset.StandardCharsets.UTF_8);
    System.out.println(java.util.Arrays.toString(byteArray));
    

    但不幸的是,它给出了以下结果:

    [65, -61, -92, 36, 36, -30, -126, -84, 104]
    

    Try it online.

    我不确定这些负值是从哪里来的。。

    给定Java中包含非ASCII字符的字符串(即。 “A·$$h” ord

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jorn Vernee    7 年前

    JAVA byte 是有符号的,这就是负数的来源。就位而言,两种语言中的数字值相同,它们的表示方式不同。通过使用 Byte.toUnsignedInt()

    String input = "Aä$$€h";
    byte[] byteArray = input.getBytes(java.nio.charset.StandardCharsets.UTF_8);
    int[] ints = new int[byteArray.length];
    for(int i = 0; i < ints.length; i++) {
        ints[i] = Byte.toUnsignedInt(byteArray[i]);
    }
    System.out.println(java.util.Arrays.toString(ints));
    

    其中打印:

    [65, 195, 164, 36, 36, 226, 130, 172, 104]