The post Know Size and Range of int or uint in Go (Golang) appeared first on Welcome To Golang By Example.
]]>Size and range of int and uint in go is platform-dependent meaning that the size and range depend whether the underlying platform is 32-bit or a 64-bit machine.
Size Table
Type | Size (32 bit machine) | Size (64 bit machine) |
int | 32 bits or 4 byte | 64 bits or 8 byte |
uint | 32 bits or 4 byte | 64 bits or 8 byte |
Range Table
Type | Size (32 bit machine) | Size (64 bit machine) |
int | -231 to 231 -1 | -263 to 263 -1 |
uint | 0 to 232 -1 | 0 to 264 -1 |
const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64
Once the size is known, the range can be deduced based upon size. See the below code for printing size.
package main
import (
"fmt"
"math/bits"
"unsafe"
)
func main() {
//This is computed as
//const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64
sizeInBits := bits.UintSize
fmt.Printf("%d bits\n", sizeInBits)
//Using unsafe.Sizeof() function. It will print size in bytes
var a int
fmt.Printf("%d bytes\n", unsafe.Sizeof(a))
//Using unsafe.Sizeof() function. It will print size in bytes
var b uint
fmt.Printf("%d bytes\n", unsafe.Sizeof(b))
}
Output:
64 bits
8 bytes
8 bytes
The post Know Size and Range of int or uint in Go (Golang) appeared first on Welcome To Golang By Example.
]]>