Reputation: 331
I have the next code which tries to convert a double type number into its binary form. I know the algorithm, the integer part of the number can be converted to binary the same way an int type number would, and the remainig fractionary part can be converted this way:
integerPart = (int)value;
fractionaryPart = value-integerPart;
while(fractionaryPart != 0.0)
{
fractionaryPart = fractionaryPart*2;
integerPart = (int)fractionaryPart;
fractionaryPart = fractionaryPart - integerPart;
}
this is the code to convert the integer part
bits = 64 //8 bytes
char binary[] = new char[bits];
for(i = bits-1;i >= 0;i--)
{
if((integerPart&1) == 1)
binary[i] = '1';
else if((integerPart&1) == 0)
binary[i] = '0';
integerPart >>= 1;
}
the problem is that I have to print the entire number the way a double number would look into the RAM memory (an 8 bytes format) for example if I have the number 42.375, the result must be 101010.011. But I don´t know how to combine the binary numbers of the while() and the for() and put them into an array of 64 bits, like:
|00000000|00000000|00000000|00000000|00000000|00000000|00000010|1010.011|
any suggestions??
Upvotes: 2
Views: 273
Reputation: 198143
That is not how double
s are represented in memory.
The above representation is for a 32-bit float, for a double it is 52 bits of mantissa, 11 bits of exponent, and 1 sign bit.
Double.doubleToLongBits
is how you get this out, and longBitsToDouble
is the reverse conversion. The Javadoc of longBitsToDouble
discusses the details of the conversion.
Upvotes: 3
Reputation: 2327
The way I've always printed a double number the way it looks in RAM is using one of the Double.doubleToLongBits or Double.doubleToRawLongBits methods in the Double class.
Upvotes: 0