记得远古时代,上第一门计算机课时,书上说:整型数字在计算机中的以补码形式保存。今天有人问我这是啥意思。我干脆就写了个程序来说明这点,程序的功能是让用户输入一个整型数字,然后将这个数字所占据的内存按照位和字节分别输出。不但可以看出的确是用补码形式保存,还能看出是little-endian还是big-endian。
#include <iostream>
#include <string>
using namespace std;
unsigned char masks[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; 发布日志
void print_8bits(unsigned char c)
{
for(int bit = 0; bit < 8; bit++)
{
cout << (((c & masks[bit]) >> (7-bit)) == 0 ? "0" : "1");
}
}
int main()
{
while(true)
{
cout << "please enter one num (q to quit):" << endl;
string str;
if (getline(cin, str))
{
if (str == "q")
{
break;
}
int i = atoi(str.c_str());
int i_0 = *((unsigned char*)(&i));
int i_1 = *((unsigned char*)(&i) + 1);
int i_2 = *((unsigned char*)(&i) + 2);
int i_3 = *((unsigned char*)(&i) + 3);
print_8bits(i_0);
cout << " ";
print_8bits(i_1);
cout << " ";
print_8bits(i_2);
cout << " ";
print_8bits(i_3);
cout << endl;
cout << hex;
cout << i_0 << " " << i_1 << " " << i_2 << " " << i_3 << endl;
cout << dec;
}
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
unsigned char masks[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; 发布日志
void print_8bits(unsigned char c)
{
}
int main()
{
}