Split double in c without any library
Hello, I have a question for a programmer c there, we have a test at school to create a soft real time system in the operating system made by our teacher.
It's good that everything is fine and dandy, we decided to create a system that calculates how many medicine combines a diabetic need based on his or her blood sugar. No need to be correct if we have an idea for a real time system: D
But we did a little damage to our formula for calculating units of medicine
[blood sugar] * 1.2
But the only way we can send messages between processes is a structure containing 8 longs, but here where my knowledge of c ends, we need to somehow split this double into 2 longs, for example: an integer in long 0 and decimal value in long 1, and then collect it on the other side. But I have no idea who is doing this and therefore needs a little help.
We tried, but we don't have access to the standard libraries.
a source to share
If you don't need particularly high precision, just use scaled integers: multiply the double by some force of ten, convert it to an integer (discarding the remaining decimal digits) and send long. Alternatively, you can simply undo these steps.
If you need more precision, you can use modf
to split the number into integral part and fractional part, and then scale only fractional part.
a source to share
Dirty trick, store the actual representation of your double in longs (assuming their size fits):
double yourVar = yourValue;
long * read = (long *)&yourVar;
yourStruct.long1 = *read;
yourStruct.long2 = *(read + 1);
And to build on the other side:
double yourVar;
long * read = (long *)&yourVar;
*read = yourStruct.long1;
*(read + 1) = yourStruct.long2;
Basically you are cheating; you get a pointer to your variable, which is double
, but you tell the compiler that it is actually a pointer to two consecutive variables long
. Then you read and write from them, but what actually happens is the underlying bit representation is shifted, in other words, the two resulting variables long
have no meaning with respect to your number (they are not integers or the decimal part for example).
Of course, this only works if:
sizeof(long) * 2 >= sizeof(double)
on your platform and provided that the communications protocol does not alter the bitwise representation of the variables in any way.
a source to share