note 90142 added to function.pack

From: Date: Tue, 07 Apr 2009 23:54:15 +0000
Subject: note 90142 added to function.pack
Groups: php.notes 
Request: Send a blank email to php-notes+get-152932@lists.php.net to get a copy of this message
These two functions allow conversion between binary string and signed integer with possibility to give the bit length. Usage: echo si2bin(-10, 32); 11111111111111111111111111110110 echo si2bin(10, 32); 00000000000000000000000000001010 echo bin2si("11111111111111111111111111110110", 32); -10 echo bin2si("00000000000000000000000000001010", 32); 10 // signed integer to binary function si2bin($si, $bits=32) { if ($si >= -pow(2,$bits-1) and $si <= pow(2,$bits-1) ) { if ($si >= 0) // positive or zero { $bin = base_convert($si,10,2); // pad to $bits bit $bin_length = strlen($bin); if ($bin_length < $bits) $bin = str_repeat ( "0", $bits-$bin_length).$bin; } else // negative { $si = -$si-pow(2,$bits); $bin = base_convert($si,10,2); $bin_length = strlen($bin); if ($bin_length > $bits) $bin = str_repeat ( "1", $bits-$bin_length).$bin; } return $bin; } } // binary to signed integer function bin2si($bin,$bits=32) { if (strlen($bin)==$bits) { if (substr($bin,0,1) == 0) // positive or zero { $si = base_convert($bin,2,10); } else // negative { $si = base_convert($bin,2,10); $si = -(pow(2,$bits)-$si); } return $si; } } ---- Server IP: 80.81.171.181 Probable Submitter: 84.249.93.137 ---- Manual Page -- http://www.php.net/manual/en/function.pack.php Edit -- https://master.php.net/note/edit/90142 Del: integrated -- https://master.php.net/note/delete/90142/integrated Del: useless -- https://master.php.net/note/delete/90142/useless Del: bad code -- https://master.php.net/note/delete/90142/bad+code Del: spam -- https://master.php.net/note/delete/90142/spam Del: non-english -- https://master.php.net/note/delete/90142/non-english Del: in docs -- https://master.php.net/note/delete/90142/in+docs Del: other reasons-- https://master.php.net/note/delete/90142 Reject -- https://master.php.net/note/reject/90142 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#152932) next »