There is a String Packet in which data is written a la FA0023CC and byte[] P = new byte[Packet.length()/2] array byte[] P = new byte[Packet.length()/2] into which you need to drive data by type 0xFA 0x00 0x23 0xCC I write bytes in this way:

 P[i]= (byte) ((Character.digit(Packet.charAt(i*2), 16) << 4) + Character.digit(Packet.charAt(i*2+1), 16)); 

where i is the byte number, everything reads correctly until I encounter bytes larger than 7F, starting from 80 they for some reason become negative and go in the opposite direction (if you convert 0x80, 0x81, 0x82 to int, it will not be 128, 129, 130, a -128, -127, -126, etc.)

  • Everything is correct - binary numbers with a unit in the first position in computer science are interpreted as negative. You would have been helped by the unsigned byte type, but there is no such thing in Java. What's the question? - Enikeyschik
  • Is it possible to correct the interpretation so that, for example, the if (P[i]==0xFF) comparison worked correctly, if the FF string was considered, and now the comparison only works correctly with 7F numbers - nikolay-rudavin

1 answer 1

Since you compare the type of byte with the type of int , then for numbers greater than 127 the following problem occurs - despite their external similarity, these are different numbers:

  • the FF number of the byte type is -1 (the binary representation is 11111111 ).
  • the int FF number (the default number type) is 255 (the binary representation is 24нуля11111111 ).

There are two ways to solve the problem:

  1. Convert byte to int , i.e. to add 24 zero in front. In this case, there is no special meaning, because we are only interested in negative numbers, and with them there will be a blink.
  2. Convert int to byte (i.e. just drop the first 24 zeros). Like this:

    (P[i] == (byte) 0xFF)

  • Thanks, decided the 2nd way - nikolay-rudavin