Tuesday, November 29, 2011

PHP to Convert Binary Data (in String Value) to Numeric Values



$string = "10101011";
echo(stringbin2num($string)); // Will return 171

function stringbin2num($input) {

 $len = strlen($input);
 $count = 0; $val = 0;

 while ($count < $len) {

  if (substr($input, $len-$count-1, 1)) {
   $val += pow(2, ($count));
  }
  $count++;
 }

 return $val;
}



This function might not be needed in many situations. It's just a reference for those who want to convert string to numbers. You can also modify these codes to handle string of HEX characters such as 'AABB'. If you are reading strings from the binary file, the best is still to use the unpack() function. Unpack function allows you convert to many formats you like.

No comments:

Post a Comment