Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP在十六进制求和值前加上1?_Php_Hex_Integer Overflow - Fatal编程技术网

PHP在十六进制求和值前加上1?

PHP在十六进制求和值前加上1?,php,hex,integer-overflow,Php,Hex,Integer Overflow,我正在研究添加几个十六进制值(base16)的东西 在常规C程序中,我执行以下操作: uint32_t test1 = 0x5BE0CD19; uint32_t test2 = 0x3587272B; uint32_t test3 = 0x1F85C98C; uint32_t test4 = 0x428A2F98; uint32_t test5 = 0x61626380; uint32_t test6 = (test1 + test2 + test3 + test4 + test5); pri

我正在研究添加几个十六进制值(base16)的东西

在常规C程序中,我执行以下操作:

uint32_t test1 = 0x5BE0CD19;
uint32_t test2 = 0x3587272B;
uint32_t test3 = 0x1F85C98C;
uint32_t test4 = 0x428A2F98;
uint32_t test5 = 0x61626380;
uint32_t test6 = (test1 + test2 + test3 + test4 + test5);

printf( "%08x \n", test6 );
结果是:

> 54da50e8
但是,在PHP中(我的PHP是64位),当我将相同的和应用于:

$test1 = 0x5BE0CD19;
$test2 = 0x3587272B;
$test3 = 0x1F85C98C;
$test4 = 0x428A2F98;
$test5 = 0x61626380;
$test6 = ($test1 + $test2 + $test3 + $test4 + $test5);

echo(sprintf( "%08x \n", $test6 ));
我得到:

> 154da50e8
奇怪的是,这个数字前面加了一个
1


这种行为有什么原因吗?如果有,我该如何防止它?

您的答案不同,因为您专门将C变量键入32位,因此加法溢出,留下结果
0x54da50e8
。但是,PHP整数的大小与安装相同,在本例中为64位,因此算术不会溢出,您可以得到正确的和:
0x154da50e8
。(请注意,您的
8
width规格为最小值,因此您可以从结果中获得所有9位数字)。如果只需要32位结果,则需要适当地屏蔽
$test6
的值,即

$test6 &= (1 << 32) - 1;
echo(sprintf( "%08x \n", $test6 ));

PHP打印正确答案,您的c-加法溢出。
54da50e8