格式将64位整数-1打印为golang和C之间的十六进制偏差 [英] Format printing the 64bit integer -1 as hexadecimal deviates between golang and C

查看:77
本文介绍了格式将64位整数-1打印为golang和C之间的十六进制偏差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在阅读 effective_go 文档,并且在阅读《 打印部分:

I'm recently reading the effective_go document, and got shocked when reading the Print section:

var x uint64 = 1<<64 - 1
fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))

打印

18446744073709551615 ffffffffffffffff; -1 -1

作为C程序员,%x int64(x)的预期输出也应该为ffffffffffffffff,所以上述输出对我来说是不合理的,有人可以告诉我为什么吗?

As a C programmer the expected output of %x int64(x) should also be ffffffffffffffff, so the above output is unreasonable to me, could anyone tell why?

推荐答案

例如,Go在这里的行为不同于C.整数的%x动词表示使用十六进制(基数16)表示形式而不是其内存表示形式(将为2的补码)格式化数字的 value . %b用于二进制,%o用于八进制表示.

Go acts differently here than C for example. The %x verb for integers means to format the value of the number using the hexadecimal (base 16) representation, not its memory representation (which would be 2's complement). Same goes for %b for binary and %o for octal representation.

对于像-255这样的负数,其base16表示形式是-ff.

For a negative number like -255, its base16 representation is -ff.

Go对类型严格,您必须始终明确.如果传递一个有符号整数,它将被格式化为一个有符号整数.如果要将其打印为无符号值,则必须像以下示例一样将其显式转换为无符号值:

Go is strict about types, you always have to be explicit. If you pass a signed integer, it will be formatted as a signed integer. If you want to print it as an unsigned value, you have to explicitly convert it to an unsigned value like in this example:

i := -1 // type int
fmt.Printf("%d %x %d %x", i, i, uint(i), uint(i))

输出(在游乐场上尝试):

-1 -1 4294967295 ffffffff

请注意,将带符号的值转换为其无符号版本(相同大小)时,它不会仅更改其类型的内存表示形式,因此转换后的值(无符号结果)将是带符号的值的2的补码.

Note that when converting a signed value to its unsigned version (same size) it does not change the memory representation just its type, so the converted value (the unsigned result) will be the 2's complement of the signed value.

关于为什么这是默认的负数,请阅读Rob Pike给出的理由

As to why this is the default for negative numbers, read the reasoning given by Rob Pike here:

为什么不是默认的[unsigned format]?因为如果是这样,将无法将某些内容打印为负数,如您所见,它的表示形式要短得多.或者换一种说法,%b%o%d%x都以相同的方式对待他们的论点.

Why is that not the default [the unsigned format]? Because if it were, there would be no way to print something as a negative number, which as you can see is a much shorter representation. Or to put it another way, %b %o %d %x all treat their arguments identically.

您可以在以下相关问题中了解如何/在何处实现此目标: Golang:Two's补码和fmt.Printf

You can see how / where this is implemented in this related question: Golang: Two's complement and fmt.Printf

这篇关于格式将64位整数-1打印为golang和C之间的十六进制偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆