Question

I have a byte array of a certain size. I would like to grab it's last four bytes and put them next to each other to form a four byte hexadecimal value, in a variable. This way I can compare a four-byte CRC-32 value with my variable and check whether the CRC values are the same. Now this is how I am doing this at the moment:

static unsigned long whole_four = 0; // This variable holds the last four bytes of the  received bytes which are the CRC bytes

//Note that "MAX_INPUT" is the size of my array and "data" is just a pointer I have used as an argument to a function to point to the elements a buffer array.

whole_four = ((unsigned long)(*(data+(MAX_INPUT-4)))<< 24)  | ((unsigned long)(*(data+(MAX_INPUT-3)))<< 16) | ((unsigned long)(*(data+(MAX_INPUT-2)))<< 8) | ((unsigned long)(*(data+(MAX_INPUT-1))));

So as you can see I am shifting and "or"ing the the last four elements of my array to make a four byte variable. Now, my question is: Is there any faster way to achieve this and reduce the amount of processing power required? I also like to mention that I am compiling this code on an Arduino Uno. Any help or hints is much appreciated.

Was it helpful?

Solution

If endian-ness isn't a issue (as Yves says if the two CRC's to be compared are obtained the same way), you could try with:

memcpy(&whole_four, data + MAX_INPUT - 4, sizeof(whole_four));

A modern compiler will inline this call to something well adapted to your situation considering data type alignment (a char array doesn't necessarily have the correct alignment) / processor.

PS memcpy will interpret the bytes of data with the host system byte order (little endian), while your method interprets the bytes from data in big-endian order.

So memcpy will only work if you can obtain the other term of comparison in the same format.

OTHER TIPS

*(unsigned long*)(data + MAX_INPUT - 4) will fetch the four bytes in a single go. Depending on indianness, this can give you two different results. But if the two CRC's to be compared are obtained the same way, it does not matter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top