Reputation: 1351
I am trying to mimick a old legacy C program behavior in Java. The C code is :
void calc_crc(unsigned char *datbuff,unsigned int length)
{
static unsigned char tmp;
static unsigned int crc,zaehler;
crc = 0;
for (zaehler = 0;zaehler < length ;zaehler ++)
{
tmp=(unsigned char) (crc>>8) ;
crc=(crc<<8) ^ crctab[tmp] ^ *datbuff;
datbuff++;
}
}
static unsigned short crctab[256] =
{ // Some values
};
The first issue is this code uses unsigned where as java is signed. Trying hard to retain those values. Can we get the same results in java too.
Upvotes: 0
Views: 417
Reputation: 631
The easiest way is to always use at least one size up. i.e. where C uses a char, you use a short or an int. In this case it will require more fiddling with the values to keep them in check, but that can be handled with masking for the most part.
The longer answer is that you can do the same operations on signed variables, but translate all the values. Also, be very careful with your shifts in java, make sure to use >>> or you'll just confuse yourself. >> is a signed right shift, >>> is unsigned. For the most part, your code may just work if you make sure to use the correct size variables and the correct shift operators.
Upvotes: 2
Reputation: 30235
You can use the next higher integral type (long instead of int,..) and mask the input correctly. 8byte values are more complicated - usually you'll have to use BigInteger in such a case - although sometimes you can use signed numbers with some tricks depending on the operations, shifts and xor work just fine independent of the sign bit.
But the problem is the given code can't "mimicked" in the first place because it is implementation defined. unsigned int
could be 2, 4 or 8 bytes - take your pick and C does not demand any specific right shift operation..
Upvotes: 2