int Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/int/ Wed, 01 Jan 2020 17:53:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 int Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/int/ 32 32 159787465 Know Size and Range of int or uint in Go (Golang) https://vikasboss.github.io/go-size-range-int-uint/ https://vikasboss.github.io/go-size-range-int-uint/#respond Wed, 01 Jan 2020 17:53:13 +0000 https://vikasboss.github.io/?p=1062 Overview int is a signed Integer data type uint is an unsigned Integer data type Size and range of int and uint in go is platform-dependent meaning that the size and range...

The post Know Size and Range of int or uint in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview
  • int is a signed Integer data type
  • uint is an unsigned Integer data type

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

TypeSize (32 bit machine)Size (64 bit machine)
int32 bits or 4 byte64 bits or 8 byte
uint32 bits or 4 byte64 bits or 8 byte

Range Table

TypeSize (32 bit machine)Size (64 bit machine)
int-231 to 231 -1-263 to 263 -1
uint0 to 232 -10 to 264 -1

Know Size and Range

  • bits package of golang can help know the size of an int or uint on your system. bits.UintSize is the const that stores this value. It is calculated as below
const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64
  • unsafe.Sizeof() function can also be used to see the size of int or unit in bytes

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.

]]>
https://vikasboss.github.io/go-size-range-int-uint/feed/ 0 1062