Assuming the code you posted works on bits, here you are a
C++
program that closely resembles it:
#include <iostream>
using namespace std;
union byte
{
struct
{
unsigned b0 : 1;
unsigned b1 : 1;
unsigned b2 : 1;
unsigned b3 : 1;
unsigned b4 : 1;
unsigned b5 : 1;
unsigned b6 : 1;
unsigned b7 : 1;
} bit;
unsigned char u8;
};
byte compute_crc(unsigned data)
{
byte crc;
byte crc_new;
crc.u8 = 0xFF;
crc_new.u8 = 0x00;
for (size_t i=0; i<24; ++i)
{
crc_new.bit.b7 = crc.bit.b6;
crc_new.bit.b6 = crc.bit.b5;
crc_new.bit.b5 = crc.bit.b4;
crc_new.bit.b4 = crc.bit.b3 ^ crc.bit.b7;
crc_new.bit.b3 = crc.bit.b2 ^ crc.bit.b7;
crc_new.bit.b2 = crc.bit.b1 ^ crc.bit.b7;
crc_new.bit.b1 = crc.bit.b0;
unsigned data_i = (data >> (23-i) ) & 1;
crc_new.bit.b0 = data_i ^ crc.bit.b7;
crc.u8 = crc_new.u8;
}
crc.u8 ^= 0xFF;
return crc;
}
int main()
{
unsigned a[] = { 0xA0CA85, 0x3B007C};
for (size_t n = 0; n < sizeof(a)/sizeof(a[0]); ++n)
{
byte crc = compute_crc(a[n]);
cout << "data = " << hex << uppercase << a[n] << ", CRC = " << (unsigned) crc.u8 << endl;
}
}
[update]
You may also use
bitset
s
#include <iostream>
#include <bitset>
using namespace std;
using byte = bitset<8>;
byte compute_crc(bitset<24> data)
{
byte crc = 0xFF;
byte crc_new = 0x00;
for (int i = 23; i>=0; --i)
{
crc_new[7] = crc[6];
crc_new[6] = crc[5];
crc_new[5] = crc[4];
crc_new[4] = crc[3] ^ crc[7];
crc_new[3] = crc[2] ^ crc[7];
crc_new[2] = crc[1] ^ crc[7];
crc_new[1] = crc[0];
crc_new[0] = data[i] ^ crc[7];
crc = crc_new;
}
crc ^= 0xFF;
return crc;
}
int main()
{
bitset<24> a[] = { 0xA0CA85, 0x3B007C };
for (size_t n = 0; n < sizeof(a)/sizeof(a[0]); ++n)
{
byte crc = compute_crc(a[n]);
cout << "data = " << hex << uppercase << a[n].to_ulong() << ", CRC = " << crc.to_ulong() << endl;
}
}