note 71356 added to function.bin2hex
| From: | ratfactor at gmail dot com | Date: | Thu, 23 Nov 2006 20:13:52 +0000 |
| Subject: | note 71356 added to function.bin2hex | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-120034@lists.php.net to get a copy of this message | ||
I also wished to have the ability to translate a string containing a binary number
('1101') to a string containing a hexadecimal number ('d'). Here is my
function:
function strbin2hex($bin){
$last = strlen($bin)-1;
for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
return dechex($x);
}
Example:
strbin2hex('1101'); // returns 'd'
I also added some optional features to my function (zero padding and upper case hex letters):
function strbin2hex($bin, $pad=false, $upper=false){
$last = strlen($bin)-1;
for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
$x = dechex($x);
if($pad){ while(strlen($x) < intval(strlen($bin))/4){ $x = "0$x"; } }
if($upper){ $x = strtoupper($x); }
return $x;
}
Examples:
strbin2hex('11110101', true, true); // returns 'F5'
strbin2hex('00001011', true, true); // returns '0B'
----
Server IP: 216.194.113.175
Probable Submitter: 70.190.126.80
----
Manual Page -- http://www.php.net/manual/en/function.bin2hex.php
Edit -- https://master.php.net/note/edit/71356
Del: integrated -- https://master.php.net/note/delete/71356/integrated
Del: useless -- https://master.php.net/note/delete/71356/useless
Del: bad code -- https://master.php.net/note/delete/71356/bad+code
Del: spam -- https://master.php.net/note/delete/71356/spam
Del: non-english -- https://master.php.net/note/delete/71356/non-english
Del: in docs -- https://master.php.net/note/delete/71356/in+docs
Del: other reasons-- https://master.php.net/note/delete/71356
Reject -- https://master.php.net/note/reject/71356
Search -- https://master.php.net/manage/user-notes.php