Reputation: 43
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.
Upvotes: 4
Views: 802
Reputation: 66234
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)
}
^uint(0)
is the uint
value in which all bits are set.0
on a 32-bit architecture, and1
on a 64-bit architecture.32
by as many places as the result of the second step yields32
on a 32-bit architecture, and64
on a 64-bit architecture.Upvotes: 5