Search code examples
javajava-me

Char from Byte Array in Java ME


Is this the correct way to bit shift into a char?

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

If not, please correct me.


Solution

  • Bytes in Java are a bit tricky. They don't go from 0 to 255 like you might be used to from other languages. Instead, they go from 0 to 127 and then from -128 to -1.

    This means, that all bytes in your byte array that is below 128 will be converted into the correct char with this code:

    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.

    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).

    So to properly convert 2 bytes into a char, you'd probably want a function like this:

    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);
    }