I'm writing a C++ program in which I need to display the bits that represent both a 32-bit and 64-bit floating point number. I had no problem properly displaying the 32-bit number, but I'm having trouble with the 64-bit number.

This is the code that I'm trying to use:

unsigned int* low = (unsigned int*)&doubleValue;
	unsigned int* high = (unsigned int*)((&doubleValue)+4);
	unsigned int mask = 0x80000000; // 1000 0000 0000 0000
	unsigned int result;

	for(int i = 31; i>=0; i--)
	{
		result = (*high & mask) >> i;
		mask = mask >> 1;
		cout << result;
	}
	mask = 0x80000000;
	for(int i = 31; i>=0; i--)
	{
		result = (*low & mask) >> i;
		mask = mask >> 1;
		cout << result;
	}

The variable 'doubleValue' is of type double and holds the number that I am trying to display in binary. I can get the lowest 32 bits to display correctly, its the highest 32 bits that I'm having trouble with.

Any help is greatly appreciated!

Does your system/compiler actually handle 64 bit values?

The 'easiest' way to handle this is to create a union using your double and a byte array. Then output the binary from the bytes.

Thanks for your replies... I just figured it out...

In case you're interested, I used an unsigned long long to loop through all 64 bits at once, rather than using two unsigned ints... I tried this before but it didn't work because of a slight error in my code.

Thanks again for your replies!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.