The maximum value for an int type in Go

前端 未结 10 1137
无人共我
无人共我 2021-01-29 19:09

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

10条回答
  •  你的背包
    2021-01-29 19:45

    I originally used the code taken from the discussion thread that @nmichaels used in his answer. I now use a slightly different calculation. I've included some comments in case anyone else has the same query as @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.

提交回复
热议问题