检测 32 位或 64 位机器(理解 `32 << (^uint(0) >> 63)` )

发布于 2025-01-17 02:04:17 字数 615 浏览 2 评论 0 原文

据说 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文