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

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 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路