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.
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.
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.
Why don't you do something like:
double *x = &value;
or a union?
It's a terrible job :)
this talks about their representation in memory (according to the IEEE754), so with various bitwise operations you have to extract the sign, the exponent and the mantissa from your's micro controller's output, then do number = (-1)^e * mantissa ^ (exponent - 1023)
.
What do you mean by saying "type casting does not work"? What exactly did you try? For example, did you try something like this:
double convert_binary_to_double(unsigned int value)
{
return *((double*)&value);
}
Have you tried using the itoa() function? It's a neat little function often used for converting int to ASCII.
To the PC their also just bytes, and as such could be copied into any 4 byte Int, 4 byte Unsigned Int or 4 byte Float field and the computer would be quite happy. You will need to envelope them, or somehow tag them as int, unsigned, or float. There is NO WAY the compiler can tell from looking at any 32 bit collection of bits what it's type is. - If you need a better explanation, comment me back and I'll give you the real long version - Joe - Maybe I misunderstod you question. I thought you wanted to ship over 4 bytes of data, and have the compuuter magucly know if the data was origenally a 32 bit Int, 32 bit Unsigned or 32 bit Float. There is no way for the computer to know the answer without additional information.
精彩评论