I have been researching about portable way to store a float
in a binary format (in uint64_t), so that it can be shared over network to various microcontroller. It should be independent of float's memory layout
and endianness
of the system.
I came across this answer. However, I am unable to understand few lines in the code which are shown below:
while(fnorm >= 2.0) { fnorm /= 2.0; shift++; }
while(fnorm < 1.0) { fnorm *= 2.0; shift--; }
fnorm = fnorm - 1.0;
// calculate the binary form (non-float) of the significand data
significand = fnorm * ((1LL<<significandbits) + 0.5f);
I am aware that the code above tries to normalize the significand
. The first line in the above code fragment is trying to get the exponent
of the float. I am not sure why second, third and fourth line are necessary. I am able to understand that second and third line of code tries to make fnorm
variable lie between 0.0
and 1.0
but why it is necesarry? Does having fnorm (in decimal format) between 0.0
and 1.0
makes sure it's binary representation will be 1.xxxxxx...
.
Please help me understanding what each step is trying to achieve what and how it achieves that? I want to understand how it changes bit-pattern of the float variable to get normalized significant (left-most bit set to 1
).