How to Get the Maximum Value for an Int Type in Go
Created
Modified
Using constant values
Since integer types use two's complement arithmetic, you can infer the min/max constant values for int and uint. For example,
package main
import (
"fmt"
)
const MaxUint8 = ^uint8(0)
const MaxUint16 = ^uint16(0)
const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1
func main() {
fmt.Printf("uint8 %+v\n", MaxUint8)
fmt.Printf("uint16 %+v\n", MaxUint16)
fmt.Printf("uint64 %+v\n", MaxUint)
}
uint8 255 uint16 65535 uint64 18446744073709551615
The predeclared architecture-independent numeric types are:
uint8 (0 to 255)
uint16 (0 to 65535)
uint32 (0 to 4294967295)
uint64 (0
18446744073709551615)
int8 (-128 to 127)
int16 (-32768 to 32767)
int32 (-2147483648 to 2147483647)
int64 (-9223372036854775808
9223372036854775807)
Using math Package
We can use math package for getting the maximal and minimal values for integers:
package main
import (
"fmt"
"math"
)
func main() {
// integer max
fmt.Printf("i64 = %+v\n", math.MaxInt64)
fmt.Printf("i32 = %+v\n", math.MaxInt32)
fmt.Printf("i16 = %+v\n", math.MaxInt16)
// integer min
fmt.Printf("i64 = %+v\n", math.MinInt64)
fmt.Printf("i32 = %+v\n", math.MinInt32)
fmt.Printf("f64 = %+v\n", math.MaxFloat64)
fmt.Printf("f32 = %+v\n", math.MaxFloat32)
}
i64 = 9223372036854775807 i32 = 2147483647 i16 = 32767 i64 = -9223372036854775808 i32 = -2147483648 f64 = 1.7976931348623157e+308 f32 = 3.4028234663852886e+38
You can see more int the math package. The constants defined in the math package:
// Mathematical constants:
const (
// 3.40282346638528859811704183484516925440e+38
MaxFloat32 = 0x1p127 * (1 + (1 - 0x1p-23))
// 1.401298464324817070923729583289916131280e-45
SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23
// 1.79769313486231570814527423731704356798070e+308
MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52))
// 4.9406564584124654417656879286822137236505980e-324
SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52
)
// Integer limit values:
const (
MaxInt = 1<<(intSize-1) - 1
MinInt = -1 << (intSize - 1)
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint = 1<<intSize - 1
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)