简体   繁体   中英

PHP pack function

Why pack() gives the same result for signed and unsigned format codes?

http://php.net/manual/en/function.pack.php

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

The packed integer is a 32/64 bit dword/qword, which holds no information whether it is signed integer or not. Interpretation of the highest bit comes on unpacking stage only.

I strongly recommend to check documentation for the API server regarding data format. Apart from interpretation of the sing bit, it should mention length of integers and byte order .

Also, please read

Caution Note that PHP internally stores integer values as signed values of a machine-dependent size (C type long)....

part of the page you referred to.

Working with binary data it is your responsibility to ensure correct packing. Ie if API server expects signed 32int, you should ensure the integer you send is no more than 2,147,483,647 (0x7FFF FFFF), otherwise it will be interpreted as a negative number; and vice versa if API server expects unsigned int32, it doesn't matter how hard you want to pack a signed integer - the result will be unpacked as a positive number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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