Bit shifting an INT

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Bit shifting an INT

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Bit shifting an INT

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Bit shifting an INT

Post 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.
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Re: Bit shifting an INT

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Bit shifting an INT

Post 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.
(#10850)
Post Reply