首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Go中int类型的最大值

Go中int类型的最大值
EN

Stack Overflow用户
提问于 2011-07-30 04:21:52
回答 9查看 246K关注 0票数 182

如何为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

EN

回答 9

Stack Overflow用户

发布于 2011-07-30 04:27:08

物理类型限制的https://golang.org/ref/spec#Numeric_types

最大值是在数学包中定义的,因此在本例中是: math.MaxUint32

当心没有溢出-递增超过max会导致回绕。

票数 81
EN

Stack Overflow用户

发布于 2017-12-02 11:58:13

我将使用math包来获取整数的最大值和最小值:

package main

import (
    "fmt"
    "math"
)

func main() {
    // 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 float64 = %+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 float64 = 1.7976931348623157e+308
max float32 = 3.4028234663852886e+38
票数 48
EN

Stack Overflow用户

发布于 2016-09-19 19:03:01

我最初使用的代码取自@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
)

最后两个步骤之所以有效,是因为正数和负数在二的补码运算中的表示方式。Numeric types上的Go语言规范部分向读者推荐了相关的Wikipedia article。我没有读过这本书,但我确实从Code by Charles Petzold一书中了解到了two的补充,这是一本非常容易理解的计算机和编码基础入门。

我将上面的代码(减去大部分注释)放入一个小integer math package中。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6878590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档