views:

33

answers:

1

Hello,

I have currently the problem that I like to send some commands to an embedded devices via bluetooth (encoded in 16 bits). Unfortunately there seems to be a conversion error in Java or at least I don't know how to handle it.

These bits are e.g. 1001 0010 1011 0010 I thought about using char for this (16bit), but sometimes it's converted by Java to 24 bits (3 printed characters), when I try to add it to a string. This depends on the integer value.

How can I get the printed ASCII (or whatever) characters here? The bluetooth-function requires a String as parameter.

        int a = 127, b = 221;  // 0-255  32 bit
            char p1 = (char) b; // 0000 0000 bbbb bbbb  16 bit
            char p2 = (char) a; // 0000 0000 aaaa aaaa  16 bit

            // bbbb bbbb aaaa aaaa
        char anUnsignedShort = (char) ((p1 << 8) | p2);  // 16 bit
        System.out.println(""+(char)2+anUnsignedShort+(char)3);
        // ???? ???? bbbb bbbb aaaa aaaa  -- 24bits sometimes. Why ???
A: 

It may be useful to know about the implicit conversions of the String Concatenation Operator +. Alternatively, consider a byte[], suitable for OutputStream:

byte[] ba = {(byte) 2, (byte) 221, (byte) 127, (byte) 3};
System.out.println(Arrays.toString(ba));

Addendum:

I need it as character - in this case 4 bytes 0x02, etc.

The same principle would apply, except you'd be getting the platform's default character encoding.

char[] ca = {(char) 2, (char) 221, (char) 127, (char) 3};
System.out.println(Arrays.toString(ca));
trashgod
The output of your code is [2, -35, 127, 3] ... I need it as character - in this case 4 bytes 0x02, ...
Nils
@Nils: I've elaborated above. If it's relevant, you'll be getting the platform's default character encoding, rather than the device's.
trashgod