官方文档说uint64是一个64位的无符号整数,这是否意味着任何uint64数字应该占用8个字节,无论它有多小或多大?
编辑:
感谢大家的回答!
当我注意到binary.PutUvarint
消耗多达10个字节来存储大uint64
时,我提出了疑问,尽管最大uint64
应该只占用8个字节。
然后我在Golang lib的源代码中找到了我的疑问:
Design note:
// At most 10 bytes are needed for 64-bit values. The encoding could
// be more dense: a full 64-bit value needs an extra byte just to hold bit 63.
// Instead, the msb of the previous byte could be used to hold bit 63 since we
// know there can't be more than 64 bits. This is a trivial improvement and
// would reduce the maximum encoding length to 9 bytes. However, it breaks the
// invariant that the msb is always the "continuation bit" and thus makes the
// format incompatible with a varint encoding for larger numbers (say 128-bit).
答案 0 :(得分:9)
根据http://golang.org/ref/spec#Size_and_alignment_guarantees:
type size in bytes
byte, uint8, int8 1
uint16, int16 2
uint32, int32, float32 4
uint64, int64, float64, complex64 8
complex128 16
所以,是的,uint64将总是占用8个字节。
答案 1 :(得分:1)
简单地说:是的,64位固定大小的整数类型总是需要8个字节。这将是一种不寻常的语言,但事实并非如此。
有些语言/平台支持可变长度数值类型,其中内存中的存储依赖于值,但是您不会在这样的类型中指定类型的位数简单的方法,因为这可能会有所不同。
答案 2 :(得分:1)
Go编程语言规范
数字类型表示整数或浮点值的集合。 预先声明的与体系结构无关的数字类型为:
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
是的,正好是64位或8个字节。
答案 3 :(得分:0)
记住简单的规则,变量类型通常经过优化以适应特定的内存空间,最小内存空间为1位。并且8位(s)= 1字节:
因此64位(s)= 8字节