优雅和安全的方式,以确定是否架构为32位或64位 [英] Elegant and safe way to determine if architecture is 32bit or 64bit

查看:222
本文介绍了优雅和安全的方式,以确定是否架构为32位或64位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题所说,有没有优雅的和安全的方式,以确定是否架构为32位或64位。通过优雅,你能想到precise,正确的,总之,清洁,聪明的方式。通过安全,想安全标准,C89 / C99和操作系统独立性任期。


解决方案

指针的大小是不是真的要考个好东西 - 没有太多标准C,您可以用该测试的结果,反正做<。 / p>

我的建议是测试((为size_t)-1),最大对象的大小将c理解:

  IF((为size_t)-1&GT; 0xffffffffUL)
    {
            的printf(&GT; 32位的\\ n);
    }
    其他
    {
            的printf(&LT; = 32位的\\ n);
    }

如果它比 0xffffffffUL 更大,那么你可以在原则上比 2 ** 32的较大的物体 - 1 字节,这似乎是比一个模糊的32位与64位更有意义的测试。

(例如,如果你知道的最大值为size_t 2 ** 32 - 1 ,那么就没有一点想的mmap() A区小于1或2 GB的。)

As title says, is there any elegant and safe way to determine if architecture is 32bit or 64bit. By elegant, you can think of precise, correct, short, clean, and smart way. By safe, think of safe in term of standard, C89/C99, and operating system independence.

解决方案

The size of pointers isn't really a good thing to test - there's not much in standard C that you can do with the result of that test anyway.

My suggestion is test ((size_t)-1), the largest object size that C understands:

    if ((size_t)-1 > 0xffffffffUL)
    {
            printf("> 32 bits\n");
    }
    else
    {
            printf("<= 32 bits\n");
    }

If it's greater than 0xffffffffUL then you can in principle have objects larger than 2**32 - 1 bytes, which seems like a more meaningful test than a nebulous "32 bits versus 64 bits".

(For example, if you know that the maximum value of size_t is only 2**32 - 1, then there's no point trying to mmap() a region bigger than 1 or 2 GB.)

这篇关于优雅和安全的方式,以确定是否架构为32位或64位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆