ord*_*ary 60 c byte endianness
可能重复:
C宏定义确定大端或小端机器?
int main()
{
int x = 1;
char *y = (char*)&x;
printf("%c\n",*y+48);
}
Run Code Online (Sandbox Code Playgroud)
如果它是小端,它将打印1.如果它是大端,它将打印0.这是正确的吗?或者将char*设置为int x始终指向最低有效位,而不管字节顺序如何?
Mar*_*cus 94
简而言之,是的.
假设我们在32位机器上.
如果它是小端,那么x
在内存中将是这样的:
higher memory
----->
+----+----+----+----+
|0x01|0x00|0x00|0x00|
+----+----+----+----+
A
|
&x
Run Code Online (Sandbox Code Playgroud)
所以(char*)(&x) == 1
,和*y+48 == '1'
.
如果它是大端,它将是:
+----+----+----+----+
|0x00|0x00|0x00|0x01|
+----+----+----+----+
A
|
&x
Run Code Online (Sandbox Code Playgroud)
所以这个会是'0'
.
pho*_*xis 21
以下将做.
unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));
Run Code Online (Sandbox Code Playgroud)
设置&x
为char *
将使您能够访问整数的各个字节,字节的顺序将取决于系统的字节顺序.
Fam*_*eng 14
这是配置脚本的大端测试:
#include <inttypes.h>
int main(int argc, char ** argv){
volatile uint32_t i=0x01234567;
// return 0 for big endian, 1 for little endian.
return (*((uint8_t*)(&i))) == 0x67;
}
Run Code Online (Sandbox Code Playgroud)
use*_*559 10
以为我知道我已经在标准中读过这个内容; 但找不到它.继续看.旧; 回答标题; 不是Q-tex; P:
以下程序将确定:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你也有这种方法 ; 来自Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
Run Code Online (Sandbox Code Playgroud)
而!is_big_endian()
不是100%要少,因为它可以混合/中.
相信这可以使用相同的方法检查只改变值0x01000000
,即0x01020304
给予:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
Run Code Online (Sandbox Code Playgroud)
但不完全确定那一个......