转到:将uint64转换为int64而不会丢失信息 [英] Go: convert uint64 to int64 without loss of information

查看:2822
本文介绍了转到:将uint64转换为int64而不会丢失信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的问题:

  var x uint64 = 18446744073709551615 
var y int64 = int64(x )

就是 y -1 。在不丢失信息的情况下,将这两种数字类型转换为使用编码器和解码器的唯一方法是什么?

  buff字节。 Buffer 
Encoder(buff).encode(x)
Decoder(buff).decode(y)

请注意,我不是在典型情况下尝试进行直接数字转换。我更关心的是维护随机数生成器的统计属性。

解决方案

作为32位。



请参阅 Go1.1发行说明(它引入了 uint64

  x:= ^ uint32(0)// x是0xffffffff 
i:= int(x)//我在32位系统上是-1,在64位
上是0xffffffff fmt.Println (i)

使用 fmt.Printf(%b\\\
,y)
可以帮助您查看正在发生的事情(请参阅 ANisus '加入

事实证明,OP小麦确认( 18446744073709551615 无论如何都是 0xffffffffffffffff (-1):参见 ANisus answer ;


The problem with the following code:

var x uint64 = 18446744073709551615
var y int64 = int64(x)

is that y is -1. Without loss of information, is the only way to convert between these two number types to use an encoder and decoder?

buff bytes.Buffer
Encoder(buff).encode(x)
Decoder(buff).decode(y)

Note, I am not attempting a straight numeric conversion in your typical case. I am more concerned with maintaining the statistical properties of a random number generator.

解决方案

Seeing -1 would be consistent with a process running as 32bits.

See for instance the Go1.1 release notes (which introduced uint64)

x := ^uint32(0) // x is 0xffffffff
i := int(x)     // i is -1 on 32-bit systems, 0xffffffff on 64-bit
fmt.Println(i)

Using fmt.Printf("%b\n", y) can help to see what is going on (see ANisus' answer)

As it turned out, the OP wheaties confirms (in the comments) it was run initially in 32 bits (hence this answer), but then realize 18446744073709551615 is 0xffffffffffffffff (-1) anyway: see ANisusanswer;

这篇关于转到:将uint64转换为int64而不会丢失信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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