Reputation: 925
i need to read serial port for my sensor board and i use this example to read data coming. but i surprised that the output data on console terminal look like this
Wÿðÿ8Ã?íÈÓÿ
because i use this System.out.print(new String(buffer,0,len));
this method just print the data each time its receive packet.
but when i used this method for hexa digit the output will write zeros before it receive any data !!
this method
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort();
String f=String.valueOf(num);
System.out.print(f);
So how to deal with this issue to translate incoming bytes to readable data in hexa !!!
Upvotes: 1
Views: 1640
Reputation: 80603
Try this instead:
final byte[] arr = new byte[] { 0x00, 0x01 }; // or whatever your byte array is
final String asHexStr = DatatypeConverter.printHexBinary(arr)
System.out.println(asHexStr);
Upvotes: 3
Reputation: 5488
You should utilize existing interfaces to their full potential. Consider using printf
.
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
boolean read = true;
while(read)
try { System.out.printf("%x",wrapped.get()); } //get each byte, print as hex
catch(BufferUnderflowException ex) { read = false; } //stop at empty buffer
}
Upvotes: 1