du8864 2017-11-30 04:42
浏览 2030
已采纳

golang如何将uint64转换为int64? [重复]

This question already has an answer here:

anyone can help me? converting uint64 to int64 pls

//fmt.Println(int64(18446744073709551615)) 
//constant 18446744073709551615 overflows int64 

var x uint64 = 18446744073709551615
var y int64 = int64(x)
fmt.Println(y) //-1 

//just like(c)signed long long
//anyone can help me pls!
//How can I using like this?

// -9223372036854775808 +9223372036854775807

func BytesToInt(b []byte) int {
    bytesBuffer := bytes.NewBuffer(b)
    var tmp int32
    binary.Read(bytesBuffer, binary.BigEndian, &tmp)
    return int(tmp)
}
</div>
  • 写回答

1条回答 默认 最新

  • doujiu9172 2017-11-30 05:48
    关注

    What you are asking (to store 18,446,744,073,709,551,615 as an int64 value) is impossible.

    A unit64 stores positive integers and has 64 bits available to hold information. It can therefore store any positive integer between 0 and 18,446,744,073,709,551,615 (2^64-1).

    An int64 uses one bit to hold the sign, leaving 63 bits to hold information about the number. It can store any value between -9,223,372,036,854,775,808 and +9,223,372,036,854,775,807 (-2^63 and 2^63-1).

    Both types can hold 18,446,744,073,709,551,616 unique integers, it is just that the uint64 range starts at zero, where as the int64 values straddle zero.

    To hold 18,446,744,073,709,551,615 as a signed integer would require 65 bits.

    In your conversion, no information from the underlying bytes is lost. The difference in the integer values returned is due to how the the two types interpret and display the values.

    uint64 will display a raw integer value, whereas int64 will use two's complement.

    var x uint64 = 18446744073709551615
    var y int64 = int64(x)
    
    fmt.Printf("uint64: %v = %#[1]x, int64: %v = %#x
    ", x, y, uint64(y))
    // uint64: 18446744073709551615 = 0xffffffffffffffff
    // int64:                    -1 = 0xffffffffffffffff
    
    
    x -= 100
    y -= 100
    fmt.Printf("uint64: %v = %#[1]x, int64: %v = %#x
    ", x, y, uint64(y))
    // uint64: 18446744073709551515 = 0xffffffffffffff9b
    // int64:                  -101 = 0xffffffffffffff9b 
    

    https://play.golang.com/p/hlWqhnC9Dh

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的