Ali Akbar Azizi
Ali Akbar Azizi

Reputation: 3506

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.

Upvotes: 0

Views: 158

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

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. I.e. 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.

Upvotes: 2

Related Questions