github.com/haraldrudell/parl@v0.4.176/ints/int-properties.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 // Package ints provide manipulation of integer types. 7 package ints 8 9 import ( 10 "math" 11 "unsafe" 12 13 "golang.org/x/exp/constraints" 14 ) 15 16 const ( 17 BitsPerByte = 8 18 ) 19 20 // IntProperties returns the properties of integer I 21 // - I is int int8 int16 int32 int64 uint 22 // uint8 uint16 uint32 uint64 uintptr 23 // - isSigned is true if I is a signed integer type 24 // - maxPositive is the largest positive number that can be assigned to I 25 // - maxNegative is the largest negative number that can be assigned to I. 26 // For unsigned types, maxNegative is 0 27 // - sizeof is the number of bytes I occupies: 1, 2, 4 or 8 for 8, 16, 32, 64-bit integers 28 func IntProperties[I constraints.Integer](variable ...I) (isSigned bool, maxPositive uint64, maxNegative int64, sizeof int) { 29 30 // determine if I is signed 31 maxPositive = math.MaxUint64 32 // i’s highest bit is 1, so if i is signed, that is a negative number -1 33 var i = I(maxPositive) 34 sizeof = int(unsafe.Sizeof(i)) // Sizeof returns uintptr 35 if isSigned = i < 0; isSigned { 36 // I is signed: max negative number is highest bit 1 all other bits zero 37 maxNegative = int64(I(1) << (sizeof*BitsPerByte - 1)) 38 // max positive number is highest bit 0 all other bits 1 39 maxPositive = uint64(^I(maxNegative)) 40 } else { 41 // I is unsigned: maxNegative is 0 42 maxPositive = uint64(i) 43 } 44 45 return 46 }