#include <iostream> using namespace std; void showIntBit(int a); void showDoubleBit(double a1); void showFloatBit(float a1); int main() { int a1 = 20; double a2 = 20.0; float a3 = 20.0f; cout << "" << sizeof(a1) <<" "<<sizeof(a2)<< " "<<sizeof(a3)<<endl; showIntBit(a1); showDoubleBit(a2); showFloatBit(a3); system("pause"); return 0; } //按位置取元素判断 int 4个字节,char 1个字节, 1个字节8位 void showIntBit(int a1) { char *c1 = (char *)&a1; char byte1; int len1 = 0; if (a1 <= 255) { len1 = 1; } else if (a1 > 255 && a1 <= 65535) { len1 = 2; } else if (a1 > 65535 && a1 < 16777215) { len1 = 3; } else { len1 = 4; } for (int i = 0; i<len1; i++) { byte1 = *c1; for (int j = 0; j<8; j++) { if (0b10000000 & byte1) { cout << "1"; } else { cout << "0"; } byte1 = byte1 << 1; } cout << " "; c1++; } cout << endl; } void showDoubleBit(double val1) { unsigned idx; unsigned char arr[sizeof val1]; memcpy(arr, &val1, sizeof val1); for (idx = CHAR_BIT * sizeof val1; idx--; ) { putc( (arr[idx / CHAR_BIT] & (1u << (idx%CHAR_BIT))) ? '1' : '0' , stdout ); } cout << endl; } void showFloatBit(float val1) { unsigned idx; unsigned char arr[sizeof val1]; memcpy(arr, &val1, sizeof val1); for (idx = CHAR_BIT * sizeof val1; idx--; ) { putc( (arr[idx / CHAR_BIT] & (1u << (idx%CHAR_BIT))) ? '1' : '0' , stdout ); } cout << endl; }
4 8 4
00010100
0100000000110100000000000000000000000000000000000000000000000000
01000001101000000000000000000000
请按任意键继续. . .