Search code examples
phpstringbinaryvariable-types

Change variable type from string to binary


I have a string like :

  $str = "01110001";

and I want to change its type to binary with :

$bin = (binary) $str;

( because I want to inverse it ) But, when I try to var_dump($bin), I get :

string(8) "01110001" 

Can anyone tell me what I'm missing ?


Solution

  • Binary is not datatype. Hence you can not cast with it.

    However you can representation of binary to decimal using bindec function.

    $bin = (string)bindec($str);
    

    Note: Every number is stored as binary in memory. So you dont have specifically convert it to binary. Just use bindec and it'll convert it to number. Then it'll be stored in 4 byte integer as binary. If its string then for every digit it'll use 8 bytes.