Convert larger value hex string into bytes using java

545 views Asked by At

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:

  1. static byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)(Integer.parseInt("C6",16) & 0xff), 0x1B};
  2. 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

2

There are 2 answers

5
Shar1er80 On BEST ANSWER

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)

public static void main(String[] args) throws Exception {
    byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)0xC6, 0x1B};
    for (byte b : bytearray) {
        System.out.printf("%d ", b);
    }
    System.out.println();

    for (byte b : bytearray) {
        System.out.printf("%d ", b & 0xFF);
    }
}

Output:

2 8 22 0 0 51 -58 27 
2 8 22 0 0 51 198 27 

OLD

public static void main(String[] args) throws Exception {
    System.out.println(Byte.MIN_VALUE);
    System.out.println(Byte.MAX_VALUE);

    System.out.println(Byte.MIN_VALUE & 0xFF);
    System.out.println((byte)-1 & 0xFF);
    System.out.println((byte)-10 & 0xFF);
    System.out.println((byte)-58 & 0xFF);
}

Output:

-128
127
128
255
246
198
2
corsiKa On

It's correct because bytes are signed in java. If you need it between 0-255 instead of -128 to 127, you nede to use a short or an int (or a long, I suppose.)

That being said, you can still send it across in that format, but when you use it, you'll need to make use of it as an int. Otherwise you'll get negative numbers forever.