Reputation:
Duplicate: Compare hexadecimal and decimal values
I'm implementing x-modem protocol in java, I'm reading serialport and storing in byte array of size 1024. then I have converted data to string I'm getting 133 bytes in a packet,problem is I'm not enable to compare hexadecimal value in string and also in bytearray. I've to find SOH i.e. 0x01,EOT=0x02
in data, but I'm unable to understand how to do it.
Here is part of thecode:
char SOH=0X01;
public void readResponse()
{
byte[] buffer = new byte[1024];
int len = -1;
String data;
try
{
while ((len = this.getIn().read(buffer)) > -1)
{
data = new String(buffer,0,len);
time = System.currentTimeMillis();
data = new String(buffer, 0, len);
System.out.println("Data length is "+data.length());
System.out.println(data);
for(int i=0;i<carray.length;i++)
{
if(data.CharAt(i)==SOH)
{
System.out.println("SOH["+i+"]"+data.CharAt(i));
}
}
}
Thanks in advance.
Upvotes: 0
Views: 3259
Reputation: 19225
You're comparing bytes with Strings - this is a Bad Thing, as you dont know what encoding Java is using to cnvert a given byte into a textual representation.
Use a ByteBuffer and do comparisons between raw bytes as they are read.
Upvotes: 1
Reputation: 308031
Don't use String
/char
when handling binary data. Use byte[]
/byte
instead. Fix that before you try to fix any other bugs.
char
is a 16-bit value in Java, it's not the same as the C char
(which is defined to be a byte). The closest thing to a C char
in Java is the byte
(which is signed, 'though).
Upvotes: 1