duanhan1392 2016-06-02 04:12
浏览 381
已采纳

Golang:二进制补码和fmt.Printf

So computers use Two's complement to internally represent signed integers. I.e., -5 is represented as ^5 + 1 = "1111 1011".

However, trying to print the binary representation, e.g. the following code:

var i int8 = -5
fmt.Printf("%b", i)

Outputs -101. Not quite what I'd expect. Is the formatting different or is it not using Two's complement after all?

Interestingly, converting to an unsigned int results in the "correct" bit pattern:

var u uint8 = uint(i)
fmt.Printf("%b", u)

Output is 11111011 - exactly the 2s complement of -5.

So it seems to me the value is internally the really using Two's complement, but the formatting is printing the unsigned 5 and prepending a -.

Can somebody clarify this?

  • 写回答

2条回答 默认 最新

  • dongma7796 2016-06-02 04:46
    关注

    I believe the answer lies in how the fmt module formats binary numbers, rather than the internal format.

    If you take a look at fmt.integer, one of the very first actions that the function does is to convert the negative signed integer to a positive one:

       165      negative := signedness == signed && a < 0
       166      if negative {
       167          a = -a
       168      }
    

    There's then logic to append - in front of the string that's output here.

    IOW -101 really is - appended to 5 in binary.

    Note: fmt.integer is called from pp.fmtInt64 in print.go, itself called from pp.printArg in the same function.

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

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)