Advertisement
OrionProgrammer

binary repr to int

Nov 15th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.92 KB | None | 0 0
  1. <?php
  2.  
  3. function binaryToDecimal ($value) {
  4.     if (gettype($value) !== 'string') {
  5.         throw new InvalidArgumentException('Argument must be a string');
  6.     }
  7.  
  8.     if (preg_match('/^[01]*$/', $value) !== 1) {
  9.         throw new InvalidArgumentException('Argument must be a sequence of 1s and 0s');
  10.     }
  11.  
  12.     $number = 0;
  13.  
  14.     for ($i = 0; $i < strlen($value); $i++) {
  15.         $number *= 2;
  16.  
  17.         if ($value[$i] === '1') {
  18.             $number += 1;
  19.         }
  20.     }
  21.  
  22.     return $number;
  23. }
  24.  
  25. $testCases = [
  26.     ['000', 0],
  27.     ['001', 1],
  28.     ['010', 2],
  29.     ['011', 3],
  30.     ['100', 4],
  31.     ['101', 5],
  32.     ['110', 6],
  33.     ['111', 7],
  34. ];
  35.  
  36. foreach ($testCases as [$input, $expected]) {
  37.     echo "Testing '$input', expecting $expected: ";
  38.  
  39.     $actual = binaryToDecimal($input);
  40.  
  41.     if ($actual === $expected) {
  42.         echo "OK\n";
  43.     } else {
  44.         echo "Failed, got $actual\n";
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement