c-如何在4字节int中打印出每个字节的内容
作者:互联网
我设计了一个C代码来检查机器的字节序.
它运作良好.但是,它不能在4字节int中打印出每个字节的内容.
#include<iostream>
using namespace std;
bool f()
{
int a = 1;
char *p = (char*)&a;
for (int i = 0 ; i < 4 ; ++i)
cout << "p[" << i << "] is " << hex << *p++ << " ";
cout << endl ;
p -= 4;
if (*p == 1) return true ; // it is little endian
else return false; // it is big endian
}
int main()
{
cout << "it is little endian ? " << f() << endl ;
return 0 ;
}
输出:
p[0] is p[1] is p[2] is p[3] is
it is little endian ? 1
为什么输出为空?
谢谢
解决方法:
问题在于* p的类型为char,因此流尝试将其值打印为ASCII字符(这可能不是可见字符的值).如果将其强制转换为int,则将获得您期望的结果:
cout << "p[" << i << "] is " << hex << static_cast<int>(*p++) << " ";
标签:byte,endianness,linux,c-4 来源: https://codeday.me/bug/20191201/2079215.html