#include #include #include // Thanks to: https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BYTE_TO_BINARY(byte) \ (byte & 0x80 ? '1' : '0'), \ (byte & 0x40 ? '1' : '0'), \ (byte & 0x20 ? '1' : '0'), \ (byte & 0x10 ? '1' : '0'), \ (byte & 0x08 ? '1' : '0'), \ (byte & 0x04 ? '1' : '0'), \ (byte & 0x02 ? '1' : '0'), \ (byte & 0x01 ? '1' : '0') // Thanks to: http://www.cplusplus.com/forum/beginner/85527/#msg458803 union { double dbl; unsigned __int8 shortInt[sizeof(double)]; } test; void displayBits(int, unsigned short[]); int main() { double dbl; std::cout << "Enter a double precision number: "; std::cin >> dbl; test.dbl = dbl; unsigned short revShortInt[sizeof(double)]; for (int i = 0; i < 8; i++) { revShortInt[7 - i] = test.shortInt[i]; } displayBits(sizeof(double), revShortInt); int signBit = (revShortInt[0] & 0b10000000) >> 7; int exponentBits = ((int)((revShortInt[0] & 0b01111111) << 4)) | (int)(revShortInt[1] & 0b11110000) >> 4; unsigned long long int fraction = ((long long int)(revShortInt[1] & 0b00001111) << 48) | ((unsigned long long int)(revShortInt[2]) << 40) | ((unsigned long long int)(revShortInt[3]) << 32) | ((unsigned long long int)(revShortInt[4]) << 24) | ((unsigned long long int)(revShortInt[5]) << 16) | ((unsigned long long int)(revShortInt[6]) << 8) | (revShortInt[7]); long long int onedFraction = fraction | 0x10000000000000; std::cout << "myDouble: " << std::setprecision(16) << test.dbl << std::endl; std::cout << "signBit: " << signBit << std::endl; std::cout << "exponentBits: " << exponentBits << std::endl; std::cout << "fraction: " << fraction << std::endl; double expValue = std::pow(2, exponentBits - 1023); std::cout << "expValue: " << expValue << std::endl; double oneValue = (std::pow(2, -52) * onedFraction); printf("oneValue: %f\n", oneValue); double newValue = expValue * oneValue; std::cout << "newValue: " << newValue << std::endl; std::cin.get(); return 0; } void displayBits(int numberOfBytes, unsigned short bits[]) { for (int i = 0; i < numberOfBytes; i++) { printf(" %02x ", bits[i]); } std::cout << std::endl; for (int i = 0; i < numberOfBytes; i++) { printf(BYTE_TO_BINARY_PATTERN" ", BYTE_TO_BINARY(bits[i])); } std::cout << std::endl; int bitCount = numberOfBytes * 8 - 1; for (int i = bitCount; i >= 0; i--) { std::cout << i / 10; if (i % 8 == 0) { std::cout << ' '; } } std::cout << std::endl; for (int i = bitCount; i >= 0; i--) { std::cout << i % 10; if (i % 8 == 0) { std::cout << ' '; } } std::cout << std::endl << std::endl; }