dongyang7152 2019-02-09 11:11
浏览 315
已采纳

uint8,int8上的算术

What is the reason for getting negative and zero results in the Arithmetic operation on unit8 and int8 data types for the given example

package main

import (
    "fmt"
)

func main() {

     var u uint8 = 255
     fmt.Println(u, u+1, u*u) // "255 0 1"
     var i int8 = 127
     fmt.Println(i, i+1, i*i) // "127 -128 1"
}

https://play.golang.org/p/_a2KHP29t5p

  • 写回答

2条回答 默认 最新

  • douan8473 2019-02-09 15:30
    关注

    As shown in the other answer, and unlike some other programming languages, Go handles all integer overflow in a well-defined manner similar to what happens on most current CPUs at assembly level.


    127 = 0111 1111 binary

    that + 1 = 1000 0000 binary

    that interpreted as signed two's complement 8 bit integer is -128.


    255 = 1111 1111 binary

    that + 1 = 1 0000 0000 binary (note 9 bits)

    That would be 256 if we had 9 bits, but we don't, we have only 8 so it becomes 0000 0000 binary, which is 0.


    Similarly for multiplication:

    127*127 = 16129 = ‭0011 1111 0000 0001‬ bin

    255 * 255 = 65025 = ‭1111 1110 0000 0001‬ bin

    Both have lower 8 bits as 0000 0001 bin = 1


    Note: most of the time, if you are relying on integer overflow, you should take a step back and think hard if this is the best way to do what you are doing. This is very low level behavior, involving exact bitwise behavior, and should always be accompanied with enough comments explaining what and why.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?