Go에서 int 유형의 최대 값
unsigned
정수 유형에 대해 표현 가능한 최대 값을 어떻게 지정 합니까?
min
일부 구조체에서 최소 및 최대 길이를 반복적으로 계산하는 아래 루프에서 초기화하는 방법을 알고 싶습니다 .
var minLen uint = ???
var maxLen uint = 0
for _, thing := range sliceOfThings {
if minLen > thing.n { minLen = thing.n }
if maxLen < thing.n { maxLen = thing.n }
}
if minLen > maxLen {
// If there are no values, clamp min at 0 so that min <= max.
minLen = 0
}
그래서 처음 비교를 통해 minLen >= n
.
https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1
독일 부분 :
정수 유형은 2의 보수 산술을 사용하므로
int
및 의 최소 / 최대 상수 값을 유추 할 수 있습니다uint
. 예를 들면const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1
@CarelZA의 의견에 따라 :
uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
물리적 유형 제한은 https://golang.org/ref/spec#Numeric_types 입니다.
최대 값은 수학 패키지에 정의되어 있으므로 귀하의 경우 : math.MaxUint32
오버플로가 없는지 확인하십시오. 최대 값을 초과하면 줄 바꿈이 발생합니다.
math
최대 값과 최소값을 얻기 위해 패키지를 사용 합니다.
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
}
출력 :
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
나는 원래 @nmichaels가 그의 답변에서 사용한 토론 스레드에서 가져온 코드를 사용했습니다. 이제 약간 다른 계산을 사용합니다. 다른 사람이 @Arijoon과 동일한 쿼리를 사용하는 경우를 대비하여 몇 가지 주석을 포함했습니다.
const (
MinUint uint = 0 // binary: all zeroes
// Perform a bitwise NOT to change every bit from 0 to 1
MaxUint = ^MinUint // binary: all ones
// Shift the binary number to the right (i.e. divide by two)
// to change the high bit to 0
MaxInt = int(MaxUint >> 1) // binary: all ones except high bit
// Perform another bitwise NOT to change the high bit to 1 and
// all other bits to 0
MinInt = ^MaxInt // binary: all zeroes except high bit
)
The last two steps work because of how positive and negative numbers are represented in two's complement arithmetic. The Go language specification section on Numeric types refers the reader to the relevant Wikipedia article. I haven't read that, but I did learn about two's complement from the book Code by Charles Petzold, which is a very accessible intro to the fundamentals of computers and coding.
I put the code above (minus most of the comments) in to a little integer math package.
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 }
}
}
Quick summary:
import "math/bits"
const (
MaxUint uint = (1 << bits.UintSize) - 1
MaxInt int = (1 << bits.UintSize) / 2 - 1
MinInt int = (1 << bits.UintSize) / -2
)
Background:
As I presume you know, the uint
type is the same size as either uint32
or uint64
, depending on the platform you're on. Usually, one would use the unsized version of these only when there is no risk of coming close to the maximum value, as the version without a size specification can use the "native" type, depending on platform, which tends to be faster.
Note that it tends to be "faster" because using a non-native type sometimes requires additional math and bounds-checking to be performed by the processor, in order to emulate the larger or smaller integer. With that in mind, be aware that the performance of the processor (or compiler's optimised code) is almost always going to be better than adding your own bounds-checking code, so if there is any risk of it coming into play, it may make sense to simply use the fixed-size version, and let the optimised emulation handle any fallout from that.
With that having been said, there are still some situations where it is useful to know what you're working with.
The package "math/bits" contains the size of uint
, in bits. To determine the maximum value, shift 1
by that many bits, minus 1. ie: (1 << bits.UintSize) - 1
Note that when calculating the maximum value of uint
, you'll generally need to put it explicitly into a uint
(or larger) variable, otherwise the compiler may fail, as it will default to attempting to assign that calculation into a signed int
(where, as should be obvious, it would not fit), so:
const MaxUint uint = (1 << bits.UintSize) - 1
That's the direct answer to your question, but there are also a couple of related calculations you may be interested in.
According to the spec, uint
and int
are always the same size.
uint
either 32 or 64 bits
int
same size asuint
So we can also use this constant to determine the maximum value of int
, by taking that same answer and dividing by 2
then subtracting 1
. ie: (1 << bits.UintSize) / 2 - 1
And the minimum value of int
, by shifting 1
by that many bits and dividing the result by -2
. ie: (1 << bits.UintSize) / -2
In summary:
MaxUint: (1 << bits.UintSize) - 1
MaxInt: (1 << bits.UintSize) / 2 - 1
MinInt: (1 << bits.UintSize) / -2
full example (should be the same as below)
package main
import "fmt"
import "math"
import "math/bits"
func main() {
var mi32 int64 = math.MinInt32
var mi64 int64 = math.MinInt64
var i32 uint64 = math.MaxInt32
var ui32 uint64 = math.MaxUint32
var i64 uint64 = math.MaxInt64
var ui64 uint64 = math.MaxUint64
var ui uint64 = (1 << bits.UintSize) - 1
var i uint64 = (1 << bits.UintSize) / 2 - 1
var mi int64 = (1 << bits.UintSize) / -2
fmt.Printf(" MinInt32: %d\n", mi32)
fmt.Printf(" MaxInt32: %d\n", i32)
fmt.Printf("MaxUint32: %d\n", ui32)
fmt.Printf(" MinInt64: %d\n", mi64)
fmt.Printf(" MaxInt64: %d\n", i64)
fmt.Printf("MaxUint64: %d\n", ui64)
fmt.Printf(" MaxUint: %d\n", ui)
fmt.Printf(" MinInt: %d\n", mi)
fmt.Printf(" MaxInt: %d\n", i)
}
참고URL : https://stackoverflow.com/questions/6878590/the-maximum-value-for-an-int-type-in-go
'code' 카테고리의 다른 글
유형에서 속성 제외 (0) | 2020.08.14 |
---|---|
Java 8 LocalDate Jackson 형식 (0) | 2020.08.14 |
요청이 asp.net mvc에서 ajax인지 확인하는 방법은 무엇입니까? (0) | 2020.08.14 |
PHP 다차원 배열 검색 (특정 값으로 키 찾기) (0) | 2020.08.14 |
자바 날짜를 한 시간 뒤로 변경 (0) | 2020.08.14 |