Sri Darshan S
Sri Darshan S

Reputation: 43

How can I determine the size of words in bits (32 or 64) on the architecture?

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

Answers (1)

jub0bs
jub0bs

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

(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.

Upvotes: 5

Related Questions