0

What really happens if we write 4 times 1B of char with 8bit pointer, and then we read that 4B with 32bit pointer? Why this is not recommended, what can happen?

  • The result will depend on the [endianness](https://en.wikipedia.org/wiki/Endianness) of the system. It's therefore not portable code. – samgak Oct 05 '16 at 07:41
  • Strict aliasing does not apply since you can always alias to an 8 bit pointer. – doron Oct 05 '16 at 07:43
  • @unwind maybe http://stackoverflow.com/questions/23848188/strict-aliasing-rule-and-char-pointers is a better duplicate – bolov Oct 05 '16 at 07:45
  • @doron Not if `CHAR_BIT > 8`. –  Oct 05 '16 at 07:57
  • @doron You can convert from pointer-to-x to pointer-to-char, but not the other way around. So strict aliasing does apply, assuming the "8 bit pointer" is a character type. – Lundin Oct 05 '16 at 08:02
  • You are right. You will have to copy the bytes into the integer – doron Oct 05 '16 at 08:10
  • @Rhymoid: No conforming compiler can define types uint8_t and int8_t unless CHAR_BIT==8. A conforming compiler, however, may define integer types other than "char", "short", "int", "long", and "long long"; if it defined an 8-bit type with no padding which was none of the above, it could use the identifiers `uint8_t` and `int8_t` to identify such a type. I would think that was a horrible idea (IMHO, there should be a pair of signed/unsigned types with some other name for that purpose) but it would allowed under the Standard. – supercat Dec 12 '16 at 17:05

1 Answers1

0

When you read the 32bits back as an integer you get the integer representation of whatever you wrote.

What you have described is a technique commonly used to deserialize binary data. The reverse procedure will serialize the data.

doron
  • 27,972
  • 12
  • 65
  • 103