将字节流转换为数字数据类型 [英] Converting byte-stream into numeric data-type

查看:31
本文介绍了将字节流转换为数字数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字节流,其中我知道 64 位值(64 位随机数)的位置.字节顺序是 Little-Endian.由于 PHP 的整数数据类型仅限于 32 位(至少在 32 位操作系统上),我如何将字节序列转换为 PHP 数字表示(我认为浮点数就足够了)?

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

推荐答案

刚刚查了Zend_Crypt_Math_BigInteger_BcmathZend_Crypt_Math_BigInteger_Gmp 的代码来解决这个问题:

Just looked up the code for Zend_Crypt_Math_BigInteger_Bcmath and Zend_Crypt_Math_BigInteger_Gmp which deals with this problem:

这基本上是 Chad Birch 发布的解决方案.

public static function bc_binaryToInteger($operand)
{
    $result = '0';
    while (strlen($operand)) {
        $ord = ord(substr($operand, 0, 1));
        $result = bcadd(bcmul($result, 256), $ord);
        $operand = substr($operand, 1);
    }
    return $result;
}

使用 GMP(大端)

相同的算法 - 只是不同的函数名称.

Using GMP (Big-Endian)

Same algorithem - just different function names.

public static function gmp_binaryToInteger($operand)
{
    $result = '0';
    while (strlen($operand)) {
        $ord = ord(substr($operand, 0, 1));
        $result = gmp_add(gmp_mul($result, 256), $ord);
        $operand = substr($operand, 1);
    }
    return gmp_strval($result);
}

将算法更改为使用 Litte-Endian 字节顺序非常简单:只需从头到尾读取二进制数据:

Changing the algorithem to use Litte-Endian byte-order is quite simple: just read the binary data from end to start:

public static function bc_binaryToInteger($operand)
{
    // Just reverse the binray data
    $operand = strrev($operand);
    $result = '0';
    while (strlen($operand)) {
        $ord = ord(substr($operand, 0, 1));
        $result = bcadd(bcmul($result, 256), $ord);
        $operand = substr($operand, 1);
    }
    return $result;
}

使用 GMP(Litte-Endian)

public static function gmp_binaryToInteger($operand)
{
    // Just reverse the binray data
    $operand = strrev($operand);
    $result = '0';
    while (strlen($operand)) {
        $ord = ord(substr($operand, 0, 1));
        $result = gmp_add(gmp_mul($result, 256), $ord);
        $operand = substr($operand, 1);
    }
    return gmp_strval($result);
}

这篇关于将字节流转换为数字数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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