简体   繁体   中英

java Inputstream with large byte then 127

I have a C++ program running on microchip that sends bytes (0x30 0x98 0xa7 ...). I receive them in an android Java application, which write these bytes to a textview in hexadecimal.

But when the microchip sends values which are large than 127 (example: character á), my textview shows unexpected hexadecimal values (example: ffffffc3 ffffffa1). And it's a problem, because I want value like 0xa0. So I tried this when value is larger than 127 :

pole[i] = receive_bytes[i] & 0xff;

But then I get: 0xc3 0xa1, but textview still doesn't show correctly just 1 byte : 0xa0

And this is my code for receiving :

if(input.available() != 0)
{                       
     input.read(receive_bytes); //receive_bytes is array byte                
}

I have less reputation to comment, so I am giving my comment here.

I think you must declare the byte array as unsigned char in C++ program at microchip then use the Java code as it is. It must work. Basically when it is declared as char in C/C++, the system stores the 2s complement value. That is the problem here.

This is a unicode encoding issue.

The character á is encoded as 0xE1 in iso8859 character set. So its value of 225 is greater than 127.

In unicode, it is encoded with the same value of 0x000000E1. It can be processed as a single character using an UTF-32 or an UTF-16 encoding, so using either a 32 or a 16 bit representation.

The same unicode character is encoded using a 8 bit representation in UTF-8 with a sequence of two consecutive bytes: 0xC3 0xA1 . Any unicode character with a value between 0x80 and 0xFF will be translated into two different characters. Some larger unicode characters can be split on more bytes, because UTF-8 is a variable length encoding.

Unfortunately it's difficult to provide more precise diagnotics as it's not clear how you send your data, nor how you receive it. But if you work with an 8 bit 8859 encoding on the C++ side, you should on the java side open the stream with the same encoding by using the appropriate charset parameter when opening the stream .

Even if you have the correct value in your Java string, there could still be an issue with the TextView , which uses UTF-8 by default. You can find the solution to this problem in this other StackOverflow answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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