Convert byte stream to numeric data type

Let's say I have a byte stream in which I know the location of the 64-bit value (64-bit nonce). Byte Order - Little-Endian. Since the PHP integer data type is limited to 32-bit (at least on 32-bit operating systems), how would I convert a byte sequence to a numerical representation of PHP (in my opinion, would a float suffice?)

$serverChallenge = substr($bytes, 24, 8); // $serverChallenge now contains the byte-sequence // of which I know that it a 64-bit value 
+1
source share
4 answers

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

Using BCmath (Big-Endian)

This is essentially a solution posted by 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; } 

Using GMP (Big-Endian)

The same algorithm - 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); } 

Changing the algorithm to use the Litte-Endian byte order is quite simple: just read the binary data from the beginning and the end:

Using BCmath (Litte-Endian)

 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; } 

Using 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); } 
+6
source

Two years late for the party, but if someone still cares: unpack is the built-in way to go here, you can unpack it as a pair of 32-bit ints or as a double.

+2
source

This seems like a general hack, but it should do the job, assuming you have BC math functions that daemonmoi recommended:

 $result = "0"; for ($i = strlen($serverChallenge) - 1; $i >= 0; $i--) { $result = bcmul($result, 256); // shift result $nextByte = (string)(ord($serverChallenge[$i])); $result = bcadd($result, $nextByte); } 
+1
source

I know this is not exactly the answer to the question, but look at the BC Math functions for handling large numbers.

0
source

All Articles