note 84897 added to ref.sockets

From: Date: Tue, 05 Aug 2008 04:25:36 +0000
Subject: note 84897 added to ref.sockets
Groups: php.notes 
Request: Send a blank email to php-notes+get-143150@lists.php.net to get a copy of this message
Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings. I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer. <?php //Converts an integer to 'byte array' (string), default to 4 'bytes' (chars) function int2string($int, $numbytes=4) { $str = ""; for ($i=0; $i < $numbytes; $i++) { $str .= chr($int % 256); $int = $int / 256; } return $str; } //Converts a 'byte array' (string) to integer function string2int($str) { $numbytes = strlen($str); $int = 0; for ($i=0; $i < $numbytes; $i++) { $int += ord($str[$i]) * pow(2, $i * 8); } return $int; } //Example echo int2string(16705, 2); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA' echo string2int('AA'); //back the other way ?> ---- Server IP: 69.147.83.197 Probable Submitter: 58.108.195.140 ---- Manual Page -- http://www.php.net/manual/en/ref.sockets.php Edit -- https://master.php.net/note/edit/84897 Del: integrated -- https://master.php.net/note/delete/84897/integrated Del: useless -- https://master.php.net/note/delete/84897/useless Del: bad code -- https://master.php.net/note/delete/84897/bad+code Del: spam -- https://master.php.net/note/delete/84897/spam Del: non-english -- https://master.php.net/note/delete/84897/non-english Del: in docs -- https://master.php.net/note/delete/84897/in+docs Del: other reasons-- https://master.php.net/note/delete/84897 Reject -- https://master.php.net/note/reject/84897 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#143150) next »