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.
Don't use
String
/char
when handling binary data. Usebyte[]
/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 Cchar
(which is defined to be a byte). The closest thing to a Cchar
in Java is thebyte
(which is signed, 'though).