Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary int to double without typecasting

I am doing some microcontroller programming in C. I am reading from various sensors 4 bytes that represent either float, int or unsigned int. Currently, I am storing them in unsigned int format in the microcontroller even though the data may be float since to a microcontroller they are just bytes. This data is then transferred to PC. I want the PC to interpret the binary data as a float or an int or an unsigned int whenever I wish. Is there a way to do that?

Ex.

unsigned int value = 0x40040000; // This is 2.0625 in double
double result = convert_binary_to_double(value); // result = 2.0625

Thanks.

PS: I tried typecasting and that does not work.

like image 697
Nihad Avatar asked Apr 06 '26 07:04

Nihad


2 Answers

Keeping in mind that what you're asking for isn't entirely portable, something like this will probably do the job:

float value = *(float *)&bits;

The other obvious possibility is to use a union:

typedef union { 
    unsigned int uint_val;
    int          int_val;
    float        float_val;
} values;

values v;
v.uint_val = 0x40040000;
float f = v.float_val;

Either will probably work fine, but neither guarantees portability.

like image 69
Jerry Coffin Avatar answered Apr 08 '26 22:04

Jerry Coffin


The shortest way is to cast the address of the float (resp int) to the address of an int (resp float) and to dereference that: for instance, double result = * (float*) &value;. Your optimizing compiler may compile this code into something that does not work as you intended though (see strict aliasing rules).

A way that works more often is to use an union with an int field and a float field.

like image 31
Pascal Cuoq Avatar answered Apr 08 '26 23:04

Pascal Cuoq