Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 377
Sri Darshan S Avatar asked Nov 01 '25 05:11

Sri Darshan S


1 Answers

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.
like image 86
jub0bs Avatar answered Nov 04 '25 21:11

jub0bs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!