2010年11月12日星期五

big & little endian

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static int
is_little_endian(void)
{
  union { int i; char b[4]; } x;
  x.i = 0x01020304;
  return x.b[0] == 0x04;
}
 
static int
is_little_endian()
{
    static const union probe {
 unsigned int num;
 unsigned char bytes[sizeof(unsigned int)];
    } p = {1U};
 
    return (p.bytes[0] == 1U);
}
//2009-9-11新增加的方法
//这是CSAPP给出的方法,不过感觉使用强制类型转换没有上面的方法直白,容易明白
static int
is_little_endian4(void)
{
    int x = 1;
    return (int)(*(char *) &x);
}
我们的computer机器有big endian and little endian之分,上面的函数提供了我们一个判断我们的机器是大端模式还是小端模式的。
第二个函数要比第一个函数写的要更优秀一些也更安全,因为不是所有的机器int类型都是32位的。

没有评论:

发表评论