使用 ruby​​ 将存储为有符号的无符号整数转换回原始值 [英] Using ruby to convert unsigned integers stored as signed back to the original value

查看:28
本文介绍了使用 ruby​​ 将存储为有符号的无符号整数转换回原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 程序将它认为是 64 位无符号整数的内容放入 Postgres 数据库中类型为 int8 的列中.对于 Postgres,int8 总是 'signed int8'(没有像 'unsigned int8' 这样的东西).因此,我的 Ruby 程序在该空间的上半部分显示从 Postgres 检索到的数字为负数.

A C-program is placing what it considers to be 64-bit unsigned integers into a column in a Postgres database that is typed as int8. To Postgres, int8 is always 'signed int8' (no such thing to it as 'unsigned int8'). So the Ruby program I have shows numbers retrieved from Postgres in the upper half of that space as negative.

在 Ruby 中,将 -ve 整数转换为 C 程序员想要的 64 位无符号整数的正确方法是什么?

What is the correct way, in Ruby, to take that -ve integer and convert it to the 64-bit unsigned integer that the C-programmer intended?

推荐答案

我不确定 Ruby 的具体情况,但基本上如果数字为负数,您需要添加 2^64.这是假设数字存储为 2 的补码,这几乎可以肯定.

I'm not sure of Ruby specifics, but essentially you need to add 2^64 if the number is negative. That's assuming the number is stored as 2's complement, which it almost certainly is.

仅供参考,2 的补码系统,本质上它将(比如)32 位数字视为数字 mod 2^32.这意味着 -1 与 2^32 - 1 或 0xFFFFFFFF 相同.事实证明,这在硬件级别使用起来非常简单.

FYI, the 2's complement system, essentially it treats a (say) 32-bit number as a number mod 2^32. This means -1 is the same thing as 2^32 - 1 or 0xFFFFFFFF. This turns out to be really simple to use at a hardware level.

这篇关于使用 ruby​​ 将存储为有符号的无符号整数转换回原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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