-1

I have a litte problem to convert a hexadecimal value to the correct char value. So i had run a wireshark and everytime a catched a hexadecimal value. The value was this (in wireshark the raw data ).

00383700177a0102081c42000000000000018fffffff7f030201000a080000000000000000184802000007080444544235508001000002080104

So now i trying to send the same command to the device. I used this code to convert the hex to ascii

String hex4 = "00383700177a0102081c42000000000000018FFFFFFF7F030201000a080000000000000000184802000007080444544235508001000002080104";

   StringBuilder output4 = new StringBuilder();
   for (int i =0; i< hex4.length(); i +=2){
       String str4 = hex4.substring(i, i+2);
       System.out.println(str4);
       output4.append((char)Integer.parseInt(str4, 16));
   }
 bw3.write(output4.toString());
  log.info(output4.toString());
  bw3.flush();

But the problem now is .. when i catch my own sended data in a wireshark i get this :

00383700177a0102081c4200000000000001c28fc3bfc3bfc3bf7f030201000a08000000000000000018480200000708044454423550c2800100

For some reasen my code send the 8f and ff data wrong ..

Can you help me to fix thing issue ? Thanks !

metalgastje
  • 105
  • 1
  • 11
  • `my code send the 8f and ff data wrong` is not very clear. Can you explain what should be the desired output or behaviour. – soufrk Jun 26 '18 at 10:12
  • 8f and ff do not represent ASCII code units. (They are 00 through 7f only.) Why do you think you are receiving ASCII anyway? And, why are you converting it as if it is ISO 8859-1? Are you sure it is text at all? – Tom Blodget Jun 26 '18 at 17:53

2 Answers2

0

The use of a StringBuilder and a BufferedWriter force a conversion from binary to text, then back to binary, but there is no rational reason for the text transition step. The flow you're transmitting is purely binary and cannot be correctly converted to text. Because of that, the text conversion step introduces a corruption of the stream.

Do not use text-related classes and stick to binary-only when you're dealing with binary streams of data.

kumesana
  • 2,495
  • 1
  • 9
  • 10
-1

You can use the javax.xml.bind.DatatypeConverter to convert your hexadecimal to ascii. As mentioned in this answer to Convert a String of Hex into ASCII in Java post, you can invoke byte char to convert hex:

String hex4 = "00383700177a0102081c42000000000000018FFFFFFF7F030201000a080000000000000000184802000007080444544235508001000002080104";
byte[] s = DatatypeConverter.parseHexBinary(hex4);
System.out.println(new String(s));
jundev
  • 159
  • 1
  • 1
  • 11