Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Know Size and Range of int or uint in Go (Golang)

Posted on January 1, 2023January 1, 2023 by admin

Table of Contents

  • Overview
  • Know Size and Range

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-231to 231-1-263to 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
  • go
  • golang
  • int
  • range
  • uint
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP