英文:
How can I determine the size of words in bits (32 or 64) on the architecture?
问题
我不需要runtime.GOARCH
,因为它只会给出编译程序的架构。我想要检测操作系统的架构,比如在一个64位的机器上运行一个32位的go
程序,我需要将其识别为64位而不是32位。
英文:
I am not looking for runtime.GOARCH
as it gives the arch of the compiled program. I want to detect the OS architecture, say I run a 32-bit go
program on a 64-bit machine, I need to identify it as 64 and not 32 bit.
答案1
得分: 4
你可以通过定义一个适当的常量(下面称为BitsPerWord
)来确定int
/uint
/uintptr
的大小,通过一些位移操作来实现。作为Go的常量,它当然是在编译时计算而不是运行时计算。
这个技巧在math
包中被使用(链接),但是相关的常量intSize
并没有被导出。
package main
import "fmt"
const BitsPerWord = 32 << (^uint(0) >> 63)
func main() {
fmt.Println(BitsPerWord)
}
解释
^uint(0)
是一个所有位都被设置的uint
值。- 将第一步的结果右移63位,得到
- 在32位架构上为
0
,以及 - 在64位架构上为
1
。
- 在32位架构上为
- 将
32
左移第二步的结果所得的位数,得到- 在32位架构上为
32
,以及 - 在64位架构上为
64
。
- 在32位架构上为
英文:
You can determine the size of int
/uint
/uintptr
by defining an appropriate constant (called BitsPerWord
below) thanks to some bit-shifting foo. As a Go constant, it's of course computed at compile time rather than at run time.
This trick is used in the math
package, but the constant in question (intSize
) isn't exported.
package main
import "fmt"
const BitsPerWord = 32 << (^uint(0) >> 63)
func main() {
fmt.Println(BitsPerWord)
}
Explanation
^uint(0)
is theuint
value in which all bits are set.- Right-shifting the result of the first step by 63 places yields
0
on a 32-bit architecture, and1
on a 64-bit architecture.
- Left-shifting
32
by as many places as the result of the second step yields
32
on a 32-bit architecture, and64
on a 64-bit architecture.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论