Hello I have a question for a c programmer out there, we have a test at school to create a soft real-time system in an operating system made by our teacher.
Well that is all fine and dandy, we have chosen to create a system that calcuate how many unites of medicine a diabetic need based on his or her blood sugar. It does not need to be correct just that we have the idea of a real time system :D
But we have hit a little snag our formula for calculating the units of medicine is
[blood sugar] * 1.2
But the only way we can send messages between processes is via a structure that contains 8 longs, but here is where my knowledge of c ends, we need for some way to split this double into 2 longs, example: the who开发者_JAVA百科le number in long 0 and the decimals in long 1 and then assemble it on the other side. But I have no idea who to do this, and therefore need a little help.
We have tried but we do not have access to c standard libraries
If you don't need particularly high precision, just use scaled integers: multiply the double by some power of ten, convert it to an integer (dropping the remaining decimal digits), and send the long. On the other end you can just undo those steps.
If you need greater precision, you can use modf
to split the number into the integral part and the fractional part, and then scale just the fractional part.
Dirty trick, store the actual representation of your double in the longs (provided that their size match):
double yourVar = yourValue;
long * read = (long *)&yourVar;
yourStruct.long1 = *read;
yourStruct.long2 = *(read + 1);
And to reassemble 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 a double
, but you tell the compiler that it's actually a pointer to two consecutive long
variables. Then, you read and write from them but what is really happening is that you are moving the underlying bit representation, in other words the two resulting long
variables have no meaning with respect to your number (they are not the integer part or the decimal part for instance).
Of course, this only works if:
sizeof(long) * 2 >= sizeof(double)
on your platform, and provided that the communication protocol doesn't alter the bitwise representation of the variables in any way.
精彩评论