Golang中的int类型和uint类型到底有多大?
作者:cyeam 时间:2024-04-25 15:04:44
在开始之前,我们先来看看uint 与 int 的区别
上面是图,下面是源码:
package main
import (
"fmt"
_ "time"
)
func main() {
a := byte(255) //11111111 这是byte的极限, 因为 a := byte(256)//越界报错, 0~255正好256个数,不能再高了
b := uint8(255) //11111111 这是uint8的极限,因为 c := uint8(256)//越界报错,0~255正好256个数,不能再高了
c := int8(127) //01111111 这是int8的极限, 因为 b := int8(128)//越界报错, 0~127正好128个数,所以int8的极限只是256的一半
d := int8(a) //11111111 打印出来则是-0000001,int8(128)、int8(255)、int8(byte(255))都报错越界,因为int极限是127,但是却可以写:int8(a),第一位拿来当符号了
e := int8(c) //01111111 打印出来还是01111111
fmt.Printf("%08b %d \n", a, a)
fmt.Printf("%08b %d \n", b, b)
fmt.Printf("%08b %d \n", c, c)
fmt.Printf("%08b %d \n", d, d)
fmt.Printf("%08b %d \n", e, e)
}
引言
今天调试一个问题,发现一个我无法理解的情况:
package main
import (
"fmt"
"math"
"runtime"
)
func main() {
var a uint = math.MaxUint64
fmt.Println("Hello, playground", a, runtime.Version())
}
把64位的数字赋值给uint,我理解uint是32位的,为啥可以编译通过?但是我接着又在 playground 上试了一把,结果是编译不过了:
constant 18446744073709551615 overflows uint
int 和 uint 到底占多大空间?
其实我一直理解是32位的。因为别的语言是这样,惯性思维了。
直接看一下官方文档:
int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.
uint和int情况差不多。翻译一下,就是说这个整形最少占32位,int和int32是两码事。
再看一下 davecheney 大神的回复(大神半夜回复 GitHub 真是敬业啊):
uint is a variable sized type, on your 64 bit computer uint is 64 bits wide.
我的理解uint类型长度取决于 CPU,如果是32位CPU就是4个字节,如果是64位就是8个字节。我的电脑是64位的,而 playground 是32位的,问题就出在这里。
More
这里就会出现一个情况,int和uint是根据 CPU 变化的,如何知道当前系统的情况?
CPU 型号:runtime.GOARCH
int的长度:strconv.IntSize
写了这么多年 Golang,int天天用,一直被我当32位处理,说来惭愧。。。
来源:http://blog.cyeam.com/json/2017/12/18/go-int-size
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python Matplotlib条形图之垂直条形图和水平条形图详解
![](https://img.aspxhome.com/file/2023/4/121694_0s.png)
Python基于Tkinter实现的记事本实例
SQL Server自动更新统计信息的基本算法
Python图像运算之图像掩膜直方图和HS直方图详解
![](https://img.aspxhome.com/file/2023/0/70710_0s.png)
python3.4爬虫demo
一个数组随机不重复问题
Python Tkinter实现简易计算器功能
![](https://img.aspxhome.com/file/2023/5/105795_0s.jpg)
Oracle的约束介绍与约束维护
详解使用vue-router进行页面切换时滚动条位置与滚动监听事件
教会你完全搞定MySQL数据库 轻松八句话
windows下mysql忘记root密码的解决方法
jQuery 取得 background-position 的值
基于Python中求和函数sum的用法详解
Python实现名片管理系统
![](https://img.aspxhome.com/file/2023/9/101469_0s.jpg)
apache部署python程序出现503错误的解决方法
Python程序中的观察者模式结构编写示例
![](https://img.aspxhome.com/file/2023/3/66823_0s.png)
JavaScript事件详细讲解
用注解编写创建表的SQL语句
![](https://img.aspxhome.com/file/2023/3/88273_0s.jpg)
apache集成php7.3.5的详细步骤
![](https://img.aspxhome.com/file/2023/9/55479_0s.png)
centos7.3 安装mysql5.7.18的详细教程
![](https://img.aspxhome.com/file/2023/0/105670_0s.png)