This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Why are we reading incorrect length ?

struct SOME_STRUCT
{
  unsigned short objectId;
  unsigned long  length;
};

We read sizeof(SOME_STRUCT) from buffer.
sizeof(SOME_STRUCT) - Not sure why the lenght is Eight bytes when the structure contains a short and a long.

The data in the buffer is as follows:

01 00 00 08 00 00 00 00 00 00

We thought we were reading six bytes from the buffer but we're reading eight bytes from it.
objectId is 0x0001
length is 0x00000000

We're using Keil compiler Armcc.Exe V4.1.0.894

It looks like we have some kind of alignment issue? Does this compiler only read from word aligned addresses ? What is the root cause of the problem ? Do we need some kind of PACK or packed keyword so compiler reads six bytes from the buffer instead of eight ?

Parents
  • The unpack code could be 100% portable by picking up the individual bytes in exactly the order you - or the sending side - has defined them to be in.

    Remember that the unpack code can't just play with void pointer and type-cast it into a short or a long. That would result in an exception if the data isn't properly aligned.

    So your code would work on a byte array and pick up byte after byte and properly shift to the correct position and merge into a short or a long number. But remember that right-shift of signed numbers behaves different from unsigned numbers depending on sign bit.

Reply
  • The unpack code could be 100% portable by picking up the individual bytes in exactly the order you - or the sending side - has defined them to be in.

    Remember that the unpack code can't just play with void pointer and type-cast it into a short or a long. That would result in an exception if the data isn't properly aligned.

    So your code would work on a byte array and pick up byte after byte and properly shift to the correct position and merge into a short or a long number. But remember that right-shift of signed numbers behaves different from unsigned numbers depending on sign bit.

Children
No data