I am trying to convert a larger value of hex string into bytes. The information which is get about converting signed bytes is the max is 0x7F equals to 127 only. But now mine I want to convert hexa value C6 into bytes which i should receive 198. Are there any ways to do this?
Currently I have tested my code using this methods:
static byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)(Integer.parseInt("C6",16) & 0xff), 0x1B};
static byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)0xC6, 0x1B};
All of this method giving me the same value -58 only.
I appreciate if someone can help me with this. Thank you
Use method 2 and don't worry about the negative values in your byte array. Bytes are signed in java, so if you want to process your bytes as 0 to 255 instead of -128 to 127, AND each byte against 0xFF. This will promote the byte to an integer and will be a value from 0 - 255.
UPDATE
Seeing a comment about how you're going to send this through a serial port, there is nothing wrong with your byte array. The receiver (if it's another Java program) will have to process the bytes by ANDing them against 0xFF. Another serial program (in C# for example) would receive bytes (0x00 - 0xFF)
Output:
OLD
Output: