How does one specify the maximum value representable for an unsigned
integer type?
I would like to know how to initialize min
in the loop below
https://golang.org/ref/spec#Numeric_types for physical type limits.
The max values are defined in the math package so in your case: math.MaxUint32
Watch out as there is no overflow - incrementing past max causes wraparound.
From math lib: https://github.com/golang/go/blob/master/src/math/const.go#L39
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("max int64: %d\n", math.MaxInt64)
}
One way to solve this problem is to get the starting points from the values themselves:
var minLen, maxLen uint
if len(sliceOfThings) > 0 {
minLen = sliceOfThings[0].minLen
maxLen = sliceOfThings[0].maxLen
for _, thing := range sliceOfThings[1:] {
if minLen > thing.minLen { minLen = thing.minLen }
if maxLen < thing.maxLen { maxLen = thing.maxLen }
}
}
I would use math
package for getting the maximal value and minimal value :
func printMinMaxValue() {
// integer max
fmt.Printf("max int64 = %+v\n", math.MaxInt64)
fmt.Printf("max int32 = %+v\n", math.MaxInt32)
fmt.Printf("max int16 = %+v\n", math.MaxInt16)
// integer min
fmt.Printf("min int64 = %+v\n", math.MinInt64)
fmt.Printf("min int32 = %+v\n", math.MinInt32)
fmt.Printf("max flloat64= %+v\n", math.MaxFloat64)
fmt.Printf("max float32= %+v\n", math.MaxFloat32)
// etc you can see more int the `math`package
}
Ouput :
max int64 = 9223372036854775807
max int32 = 2147483647
max int16 = 32767
min int64 = -9223372036854775808
min int32 = -2147483648
max flloat64= 1.7976931348623157e+308
max float32= 3.4028234663852886e+38
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
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
A lightweight package contains them (as well as other int types limits and some widely used integer functions):
import (
"fmt"
"<Full URL>/go-imath/ix"
"<Full URL>/go-imath/ux"
)
...
fmt.Println(ix.Minimal) // Output: -2147483648 (32-bit) or -9223372036854775808 (64-bit)
fmt.Println(ix.Maximal) // Output: 2147483647 or 9223372036854775807
fmt.Println(ux.Minimal) // Output: 0
fmt.Println(ux.Maximal) // Output: 4294967295 or 18446744073709551615