Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
This dereferencing pointer in C works fine, but it looks wrong

This C code works fine (the compiler is GNU11). I'm sure it can improved since it gives a "dereferencing type-punned pointer" warning, but I don't know exactly how.

A uint8_t array contains 4 bytes that compose a floating point number. These 4 bytes are then stored in a uint32_t variable, and finally casted into a float variable:

uint8_t  buffer[];
uint32_t aux = 0;
float    value;

/*buffer contains the response from a sensor, containing a floating point number divided in 4 bytes*/

aux   = aux | ((buffer[3] << 24) | (buffer[4] << 16));
aux   = aux | ((buffer[5] << 8)  | (buffer[6]));
value = (float)*((float*)&aux);

Can this code present undefined behavior? I've read that I could use "union" get rid of the warning, but will will this get rid of the undefined behavior too?

Thank you!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The well defined method for type punning is using a memcpy between variables of the different types. I.e.

memcpy(&value, &aux, sizeof(float));

With optimization enabled and operating variables residing in automatic storage (i.e. regular function variables), this will translate into zero additional instructions, as the compiler will internally perform a single static assignment.

EDIT: Since C99 the other well defined method is using a union for type punning:

union {
    uint8_t  u8[sizeof(float)/sizeof(uint8_t)];
    uint32_t u32[sizeof(float)/sizeof(uint32_t)];
    float    flt;
} float_type_punner;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda