Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is pack('i',1) always 4 bytes?

Tags:

php

pack

On my machine PHP_INT_SIZE is 8 but pack('i',1) returns a 4 byte string anyway.

The docs say i is a "signed integer (machine dependent size and byte order)" but that doesn't appear to be true. Is it fixed at 4 bytes?

This means that unpack('i',pack('i',PHP_INT_MAX))[1] !== PHP_INT_MAX on 64-bit machines because half the data is lopped off.

like image 762
mpen Avatar asked Sep 30 '22 08:09

mpen


1 Answers

It's important to remember that PHP is written in C (in other words, it doesn't matter what PHP thinks an int is). Jumping off of the other answer about sizeof(int), it looks like it's a relic of 32 bit C compilers (emphasis mine)

Yes, it depends on both processors (more specifically, ISA, instruction set architecture, e.g., x86 and x86-64) and compilers including programming model. For example, in 16-bit machines, sizeof (int) was 2 bytes. 32-bit machines have 4 bytes for int. It has been considered int was the native size of a processor, i.e., the size of register. However, 32-bit computers were so popular, and huge number of software has been written for 32-bit programming model. So, it would be very confusing if 64-bit computer would have 8 bytes for int. Both Linux and Windows remain 4 bytes for int. But, they differ in the size of long.

So, in short, it could be 2 bytes but only if you have a 16 bit processor. In 32 and 64 bit systems, C seems to say int is 4 bytes in all cases. So, yes, pack('i',1); will always be 4 bytes.

like image 112
Machavity Avatar answered Nov 04 '22 02:11

Machavity