I have the following code in C to calculate a CRC16-USB for some data flows:
uint16_t DRV_CANFDSPI_CalculateCRC16(uint8_t* data, uint16_t size)
{
uint16_t init = CRCBASE;
uint8_t index;
while (size-- != 0) {
index = ((uint8_t*) & init)[1] ^ *data++;
init = (init << 8) ^ crc16_table[index];
}
return init;
}
Where crc16_table is an array of some hex values of 2 bytes (like 0xAFF3) , and data is an array of hex values of 1 byte (like 0xA3) representing the data stream (aqcuired by other means). Size is the length of the data array.
I want to reproduce this piece of code in Python, but I don't know that this statement means:
index = ((uint8_t*) & init)[1] ^ *data++;
I would like to understand that does this statament means and does, so I can reproduce it in Python. I am not an expert in C but have some knowledge, and I mostly undestand the rest of the code, but this line is giving me a headache.
Thanks and have a nice day!
init
has type uint16_t
, so the expression &init
has type "pointer to uint16_t
", or uint16_t *
. The expression (uint8_t *) &init
means "get the address of init
, but treat that as the address of a uint8_t
object, rather than a uint16_t
object".
That address is then used with a subscript operator - ((uint8_t *) &init)[1]
, which is basically equivalent to "treat init
as an array of two uint8_t
objects, and give me the value of the second element in that array".
Graphically:
+---+
init: | | <-- ((uint8_t *) &init)[0]
+---+
| | <-- ((uint8_t *) &init)[1]
+---+
So, basically, you're grabbing the lower 8 bits of init
, bitwise XORing that with the value of the current byte of the input message, and then advancing data
to point to the next byte of the input message.