Page 1 of 1

Bit shifting an INT

Posted: Mon Sep 16, 2013 3:37 pm
by dimxasnewfrozen
I have a socket that I need to send data to at byte level. I'm looking to send 6 bytes over the socket and set each byte to a specific value using bit shifting and/or the pack method (I think).

I understand that a php int is 32 bytes. Logically, I'm looking to do something like this but can't seem to get the right value.

Code: Select all

$size= 50;
$type = 1

$buffer[0] = $size >> 24;
$buffer[1] = $size >> 16;
$buffer[2] = $size  >> 8;
$buffer[3] = $size  >> 0;

$buffer[4] = $type >> 24;
$buffer[5] = $type >> 0;
I found something that used this notation which I also tried but don't quite understand.

Code: Select all

$data= pack("CCCn", 0xFF, $type, ($type >>24), ($size >>24), ($size >>16), ($size >>8),  ($size >>0)); // positive this is not correct
any ideas how I can achieve this?

Re: Bit shifting an INT

Posted: Mon Sep 16, 2013 5:46 pm
by requinix
pack() can do all the work for you if you can recognize the types of data.

$size: unsigned (probably) long integer (four bytes)
$type: unsigned (probably) short integer (two bytes)

Then you have to pick the endian-ness. Does 50 = hex 32 encode to 0x0032 (big-endian) or 0x3200 (little-endian)?

pack() has formatting characters for every combination - no bit-shifting required.

Re: Bit shifting an INT

Posted: Mon Sep 16, 2013 6:24 pm
by Weirdan
PHP integers are platform-dependent. On 64bit platforms they are 64 bits. See the value of PHP_INT_SIZE constant if you need to check for int length at runtime.

Re: Bit shifting an INT

Posted: Tue Sep 17, 2013 8:16 am
by dimxasnewfrozen
Great thanks! I checked PHP_INT_SIZE is 32bit.

// this actually works...
$unsigned_short = pack("n", $type);

I thought there was much more to it.

Re: Bit shifting an INT

Posted: Tue Sep 17, 2013 12:22 pm
by Christopher
dimxasnewfrozen wrote:I thought there was much more to it.
There was "much more to it." It was the intellect and years of experience behind the answers from two of the most knowledgeable PHP developers I know. I see posts day-after-day, and for some reason this thread really struck me.