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 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染