uint8_t in_bytes[1024];
int zoffset = 0;
uint16_t CRCget;
CRCget = *((uint16_t *) (in_bytes[5])); // no exception
CRCget = *((uint16_t *) (in_bytes[5 + zoffset])); // raise exception
Also have different reaction on array defenition
-
uint8_t in_bytes[1024];
-
uint8_t * in_bytes = new uint8_t[1024];
in_bytes[0] // equally 1th and 2nd variants
uint16_t datasize = *((uint16_t *) &in_bytes[3]); // 1th variant is done, but 2nd variant raised exception
in_bytes[5]
is a uint8_t. You can't cast that to a pointer.
In fact, you cannot cast any pointer to a different type, this is not allowed by the Standard. If you want to reinterpret the bit pattern of two uint8_ts to a uint16_t, the only valid way is to use memcpy:
uint8_t in_bytes[1024];
uint16_t CRCget;
memcpy(&CRCget, &in_bytes[5], sizeof(CRCget));
A more portable solution that deals with Endianness correctly would be:
uint8_t in_bytes[1024];
uint16_t CRCget = (uint16_t(in_bytes[5]) << 8) | in_bytes[6];
Pieter
alexey_nikitayev:
P.S.
This is not C...
Where did I talk about C? If you're using the Arduino IDE, then it's most likely C++.
Reinterpretation of raw bit patterns is one of the only valid uses of memcpy in C++, at least until C++20's std::bit_cast becomes available on Arduino (most Arduino Cores are still on C++11).
All good with memcpy!
uint8_t in_bytes[1024];
...
uint16_t CRCget;
memcpy(&CRCget, &in_bytes[datasize + 5], sizeof(CRCget));
Serial.println("CRC16 -> " + String(CRCget));
uint16_t CRCcalc = GetCrc16Table(in_bytes, datasize + 5);
Serial.println("CRC calculated -> " + String(CRCcalc));
if (CRCcalc == CRCget)
{
Serial.println("CRC Ok");
.....
Output from Serial:
All bytes received
CRC16 -> 59441
CRC calculated -> 59441
CRC Ok