10

官方文档说 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).
4

4 回答 4

13

根据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 个字节。

于 2013-06-25T06:19:06.490 回答
1

简单地说:是的,一个 64 位固定大小的整数类型总是占用 8 个字节。如果情况并非如此,那将是一种不寻常的语言。

有些语言/平台支持可变长度数字类型,其中内存中的存储确实取决于值,但是您不会以如此简单的方式指定类型中的位数,因为它可能会有所不同。

于 2013-06-25T05:47:29.290 回答
1

Go 编程语言规范

数值类型

数字类型表示整数或浮点值的集合。预先声明的独立于体系结构的数字类型是:

uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

是的,正好是 64 位或 8 个字节。

于 2013-06-25T05:47:58.477 回答
1

只要记住简单的规则,变量类型通常会被优化以适应特定的内存空间,最小内存空间是 1 位。并且 8 位 = 1 字节:

因此 64bit(s) = 8 byte(s)

于 2013-06-25T09:00:56.537 回答