Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert crc8 function in C to Java

Tags:

java

c

crc

I received a CRC function written in C from a hardware partner. Messages send by his devices are signed using this code. Can anyone help me to translate it to Java?

int8 crc8(int8*buf, int8 data_byte)
{
    int8 crc=0x00;
    int8 data_bit=0x80;
    while(data_byte>0)
    {
        if(((crc&0x01)!=0)!=((buf[data_byte]&data_bit)!=0))
        {
            crc>>=1;
            crc^=0xCD;
        }
        else 
            crc>>=1;
        data_bit>>=1;
        if(!data_bit)
        {
            data_bit=0x80;
            data_byte--;
        }
    }
    return(crc);
}

I tried to convert this to Java, but the result is not I expect.

public static byte crc8(byte [] buf, byte data_byte)
{
  byte crc = 0x00;
  byte data_bit = (byte)0x80;
  while(data_byte>0)
  {
    if(((crc&0x01)!=0)!=((buf[data_byte]&data_bit)!=0))
    {
      crc>>=1;
      crc^=0xCD;
    }
    else
    {
      crc>>=1;
    }
    data_bit>>=1;
    if(data_bit == 0)
    {
      data_bit= (byte)0x80;
      data_byte--;
    }
  }
  return crc;
}

I suppose that this is the error: if(data_bit != 0)

EDIT:

I changed the code to byte in my conversion method. I receive my data from a socket and convert this then to a String where I get a byteArray out from.

An input example is 16, 0, 1, -15, 43, 6, 1, 6, 8, 0, 111, 0, 0 ,49 where the last field (49) should be the checksum

I also tried Durandals version, but my result is still not valid.

This is how I read the data

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
char[] buffer = new char[14];
int count= bufferedReader.read(buffer, 0, 14); 
String msg = new String(buffer, 0, count);
byte[] content = msg.getBytes();
like image 323
user2952987 Avatar asked Feb 12 '26 20:02

user2952987


1 Answers

if(!data_bit)

translates to

if(data_bit == 0)

You really need to use bytes and not shorts. To get around the problem you had using bytes, use this

byte data_bit = (byte)0x80;

Also, as Mark says, you need to use >>> instead of >>.

like image 107
Charlie Burns Avatar answered Feb 15 '26 08:02

Charlie Burns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!