简体   繁体   English

如何在php中将字节数组转换为整数?

[英]How to convert byte array to integer in php?

I have seen a code that converts integer into byte array . 我见过一个将整数转换为字节数组的代码。 Below is the code on How to convert integer to byte array in php 3 ( How to convert integer to byte array in php ): 下面是关于如何在php 3中将整数转换为字节数组的代码( 如何在php中将整数转换为字节数组 ):

<?php

$i = 123456;
$ar = unpack("C*", pack("L", $i));

print_r($ar);
?>

The above code will output: 上面的代码将输出:

//output:
Array
(
   [1] => 64
   [2] => 226
   [3] => 1
   [4] => 0
)

But my problem right now is how to reverse this process. 但我现在的问题是如何扭转这一过程。 Meaning converting from byte array into integer . 意味着从字节数组转换为整数 In the case above, the output will be 123456 在上面的例子中,输出将是123456

Can anybody help me with this. 任何人都可以帮助我。 I would be a great help. 我会帮助很大。 Thanks ahead. 谢谢你。

Why not treat it like the math problem it is? 为什么不把它当成数学问题呢?

$i = ($ar[3]<<24) + ($ar[2]<<16) + ($ar[1]<<8) + $ar[0]; $ i =($ ar [3] << 24)+($ ar [2] << 16)+($ ar [1] << 8)+ $ ar [0];

Since L is four bytes long, you know the number of elements of the array. 由于L是四个字节长,因此您知道数组的元素数。 Therefore you can simply perform the operation is reverse: 因此您可以简单地执行相反的操作:

$ar = [64,226,1,0];
$i = unpack("L",pack("C*",$ar[3],$ar[2],$ar[1],$ar[0]));

In order to get a signed 4-byte value in PHP you need to do this: 为了在PHP中获得带符号的4字节值,您需要执行以下操作:

$temp = ($ar[0]<<24) + ($ar[1]<<16) + ($ar[2]<<8) + ($ar[3]);
if($temp > 2147483648)
     $temp -= 4294967296;

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

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