Pierrot Pierrot - 4 years ago 55
C Question

Converting pointer to concatenate

I have a little problem in my C-Embedded software. In fact I would like to convert a char pointer on integer pointer but I encounter some issues...

In fact I fill a char-table and would like to read this buffer in integer variable. Could a cast permits to concatenate 4-char to one integer ?

Example:

char tab[4] = {0x01,0x02,0x03,0x04};


and I would like to get an integer containing the value
0x01020304
. I tried to do that but I don't get the wanted value:

val_int =*((int*)tab);


Could you give me some advice? Is it mandatory to cast each cell once?

Answer Source

You cannot write code like this, as it violates the "strict aliasing" rule. Which, simply put, dictates that the compiler is free to assume that your array of characters is never accessed through a pointer to int. Because of this, the compiler might optimize away large portions of your code.

For example, it might decide that the whole char array is never used by your program and remove it entirely. Therefore the outcome of your code has undefined behavior.

That being said, even if your code would work as you intended, it would still be endianess-dependent. If portability/endianess is no concern, then you could use a union, which would make the code safe against pointer aliasing bugs:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

typedef union
{
  uint32_t val32;
  uint8_t  val8 [sizeof(uint32_t)];
} val_t;


int main (void)
{
  val_t v = {.val8 = {0x01,0x02,0x03,0x04} };

  printf("%.8" PRIx32, v.val32);

  return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download