简体   繁体   English

Java ME中字节数组的字符

[英]Char from Byte Array in Java ME

Is this the correct way to bit shift into a char? 这是转换成char的正确方法吗?

char value = (char)((array[offset] << 9) + (array[offset + 1]));

If not, please correct me. 如果没有,请纠正我。

Bytes in Java are a bit tricky. Java中的字节有些棘手。 They don't go from 0 to 255 like you might be used to from other languages. 它们不会从0扩展到255,就像您可能习惯其他语言一样。 Instead, they go from 0 to 127 and then from -128 to -1. 而是从0到127,然后从-128到-1。

This means, that all bytes in your byte array that is below 128 will be converted into the correct char with this code: 这意味着,您的byte数组中所有低于128的byte都将通过以下代码转换为正确的 char

char value = (char)((array[offset] << 8) + (array[offset + 1]));

But if the byte value is above 127, you'll probably get results you didn't expect. 但是,如果byte值大于127,则可能会得到意想不到的结果。

Small example: 小例子:

class test {

  public static void main(String[] args) {

    byte b = (byte)150;
    char c = (char)b;
    int i = (int)c;

    System.out.println(b);
    System.out.println(c);
    System.out.println(i);

  }
}

Will output this: 将输出以下内容:

-106
ヨ
65430

Not exactly what you might expect. 不完全是您所期望的。 (Depending of course how well you know Java). (当然取决于您对Java的了解程度)。

So to properly convert 2 bytes into a char, you'd probably want a function like this: 因此,为了将2个字节正确转换为char,您可能需要这样的函数:

char toChar(byte b1, byte b2) {
  char c1 = (char)b1;
  char c2 = (char)b2;
  if (c1<0) c1+=256;
  if (c2<0) c2+=256;
  return (char)((c1<<8)+c2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM