'Detect 32 or 64 bits machine (Understanding `32 << (^uint(0) >> 63)` )
It is said that the 32 << (^uint(0) >> 63)
expression can be used to detect whether the machine is 32 or 64 bits.
How so?
UPDATE:
The question was closed because of How can I determine the size of words in bits (32 or 64) on the architecture?
however, that answer has two problems,
- on a 32-bit architecture, the result of the first step yields 0, and no matter how you shift it, the result of the second step will always be 0 (the given answer is wrong).
- Moreover, as per The Go Programming Language, the constant are compiled at the compile time, so that
const BitsPerWord
will be a fixed value, the same asruntime.GOARCH
which gives the arch of the compiled program, and cannot be used to detect the OS architecture no matter which one it runs on.
UPDATE:
Found that the most reliable and portable way is to check with this under Linux:
$ getconf LONG_BIT
64
It won't depend on the language implementation of any programming language, and it can be used in shell scripts too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|