据说 32 << (^uint(0) >> 63)
表达式可以用来检测机器是32位还是64位。
为何如此?
更新:
该问题已关闭,因为
如何确定架构上单词的大小(32 或 64)?
但是,这个答案有两个问题,
- 在32位架构上,第一步的结果为0,无论如何移位,第二步的结果将始终为0(给出的答案是错误的)。
- 此外,根据 Go 编程语言,常量是在编译时编译的,因此 const BitsPerWord 将是一个固定值,与运行时相同。 GOARCH给出了编译后的程序的架构,无论运行在哪一种操作系统上,都不能用于检测操作系统架构。
更新:
发现最可靠和可移植的方法是在Linux下检查:
$ getconf LONG_BIT
64
它不依赖于任何编程语言的语言实现,并且它也可以在shell脚本中使用。
It is said that the 32 << (^uint(0) >> 63)
expression can be used to detect whether the machine is 32 or 64 bits.
How so?
UPDATE:
The question was closed because of
How can I determine the size of words in bits (32 or 64) on the architecture?
however, that answer has two problems,
- on a 32-bit architecture, the result of the first step yields 0, and no matter how you shift it, the result of the second step will always be 0 (the given answer is wrong).
- Moreover, as per The Go Programming Language, the constant are compiled at the compile time, so that
const BitsPerWord
will be a fixed value, the same as runtime.GOARCH
which gives the arch of the compiled program, and cannot be used to detect the OS architecture no matter which one it runs on.
UPDATE:
Found that the most reliable and portable way is to check with this under Linux:
$ getconf LONG_BIT
64
It won't depend on the language implementation of any programming language, and it can be used in shell scripts too.
发布评论