将字节流转换为数字数据类型
假设我有一个字节流,其中我知道 64 位值(64 位随机数)的位置。 字节顺序为 Little-Endian。 由于 PHP 的整数数据类型仅限于 32 位(至少在 32 位操作系统上),我如何将字节序列转换为 PHP 数字表示形式(我认为浮点就足够了)?
$serverChallenge = substr($bytes, 24, 8);
// $serverChallenge now contains the byte-sequence
// of which I know that it's a 64-bit value
Let's say I have a byte-stream in which I know the location of a 64-bit value (a 64-bit nonce). The byte-order is Little-Endian. As PHP's integer data-type is limited to 32-bit (at least on 32-bit operating systems) how would I convert the byte-sequence into a PHP numeric representation (float would be sufficient I think)?
$serverChallenge = substr($bytes, 24, 8);
// $serverChallenge now contains the byte-sequence
// of which I know that it's a 64-bit value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需查找处理此问题的
Zend_Crypt_Math_BigInteger_Bcmath
和Zend_Crypt_Math_BigInteger_Gmp
的代码:Using BCmath (Big-Endian)
这本质上是 乍得·伯奇。
使用 GMP(Big-Endian)
相同的算法 - 只是函数名称不同。
更改算法以使用 Litte-Endian 字节顺序非常简单:只需从头到尾读取二进制数据:
使用 BCmath (Litte-Endian)
使用 GMP (Litte-Endian)
Just looked up the code for
Zend_Crypt_Math_BigInteger_Bcmath
andZend_Crypt_Math_BigInteger_Gmp
which deals with this problem:Using BCmath (Big-Endian)
This is essentially the solution posted by Chad Birch.
Using GMP (Big-Endian)
Same algorithem - just different function names.
Changing the algorithem to use Litte-Endian byte-order is quite simple: just read the binary data from end to start:
Using BCmath (Litte-Endian)
Using GMP (Litte-Endian)
这看起来像是一个彻底的黑客攻击,但它应该可以完成这项工作,假设你有 daemonmoi 推荐的 BC Math 函数:
This seems like a total hack, but it should do the job, assuming you have the BC Math functions that daemonmoi recommended:
聚会迟到了两年,但如果有人仍然关心的话:
unpack 是这里的内置方法,您可以将其解包为几个 32 位整数,或作为一个双精度数。
Two years late to the party, but if anyone still cares:
unpack is the built-in way to go here, you can unpack it as a couple of 32-bit ints, or as a double.
我知道这并不是问题的答案,但请查看 BC 数学函数来处理大数。
I know this is not quite the answer to the question, but check out the BC Math functions to handle big numbers.