简体   繁体   English

LUA 5.4 - 如何将 64 位数字转换为十六进制

[英]LUA 5.4 - How to convert 64-bit numbers to hex

I wanted to convert numbers greater than 64 bits, including up to 256 bits number from decimal to hex in lua.我想在 lua 中将大于 64 位的数字(包括最多 256 位的数字从十进制转换为十六进制)。

Example:例子:

num = 9223372036854775807
num = string.format("%x", num)
num = tostring(num)
print(num) -- output is 7fffffffffffffff

but if I already add a single number, it returns an error in the example below:但如果我已经添加了一个数字,它会在下面的示例中返回错误:

num = 9223372036854775808
num = string.format("%x", num)
num = tostring(num)
print(num) -- error lua54 - bad argument #2 to 'format' (number has no integer representation)

Does anyone have any ideas?有没有人有任何想法?

I wanted to convert numbers greater than 64 bits, including up to 256 bits number from decimal to hex in lua.我想在 lua 中将大于 64 位的数字(包括最多 256 位的数字从十进制转换为十六进制)。

Well that's not possible without involving a big integer library such as this one .好吧,如果不涉及像这个这样的大型 integer 库,这是不可能的。 Lua 5.4 has two number types: 64-bit signed integers and 64-bit floats, which are both to limited to store arbitrary 256-bit integers. Lua 5.4 有两种数字类型:64 位有符号整数和 64 位浮点数,它们都被限制为存储任意 256 位整数。

The first num in your example, 9223372036854775807 , is just the upper limit of int64 bounds ( -2^63 to 2^63-1 , both inclusive).您示例中的第一个 num 9223372036854775807只是 int64 边界的上限( -2^632^63-1 ,包括两者)。 Adding 1 to this forces Lua to cast it into a float64, which can represent numbers way larger than that at the cost of precision.对此加1会强制 Lua 将其转换为 float64,它可以表示比精度大得多的数字。 You're then left with an imprecise float which has no "integer representation" as Lua tells you.然后你会留下一个不精确的浮点数,它没有“整数表示”,因为 Lua 告诉你。

You could trivially reimplement %x yourself, but that wouldn't help you extend the precision/size of floats & ints.可以自己轻松地重新实现%x ,但这无助于您扩展浮点数和整数的精度/大小。 You need to find another number representation and find or write a bigint library to go with it.您需要找到另一个数字表示,并使用它找到或写入 go 的 bigint 库。 Options are:选项是:

  • String representation: Represent numbers as hex- or bytestrings (base 256).字符串表示:将数字表示为十六进制或字节字符串(基数 256)。
  • Table representation: Represent numbers as lists of numbers (base 2^x where x is < 64)表格表示:将数字表示为数字列表(以 2^x 为底,其中 x < 64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM