你可以通过查看计算机的体系结构来确定字的大小(32位或64位)。

huangapple go评论86阅读模式
英文:

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)
}

Playground

解释

  1. ^uint(0) 是一个所有位都被设置的uint值。
  2. 将第一步的结果右移63位,得到
    • 在32位架构上为0,以及
    • 在64位架构上为1
  3. 32左移第二步的结果所得的位数,得到
    • 在32位架构上为32,以及
    • 在64位架构上为64
英文:

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 &quot;fmt&quot;

const BitsPerWord = 32 &lt;&lt; (^uint(0) &gt;&gt; 63)

func main() {
	fmt.Println(BitsPerWord)
}

(Playground)

Explanation

  1. ^uint(0) is the uint value in which all bits are set.
  2. Right-shifting the result of the first step by 63 places yields
  • 0 on a 32-bit architecture, and
  • 1 on a 64-bit architecture.
  1. Left-shifting 32 by as many places as the result of the second step yields
  • 32 on a 32-bit architecture, and
  • 64 on a 64-bit architecture.

huangapple
  • 本文由 发表于 2021年10月5日 13:48:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/69445434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定