Reputation: 485
I have the following problem, is it possible to convert a string to a binary in PHP?
The problem is that I don´t really mean conversion as such, what I mean is for example:
String = 101010
convert this variable to binary 0b101010
The user inputs the string in a form, which is sent to the script via GET. And I need to create a binary which looks "exactly like this", not conversion of the actual string to binary value.
Upvotes: 3
Views: 7818
Reputation: 4878
Unlike the phplover's answer, it seems to me that you don't want to convert the string at all.
Normally the 0b
prefix is used for binary literals or to assign to an int
variable or constant.
While PHP does not have a binary type, it's enough to have a binary string or an array which represents that kind of data.
$str = '110101';// binary for 53
//or array($str[0], $str[1], ...)
The string may be used like this:
$int = intval($str, 2);
echo $int; //prints 53
echo decbin($int); //prints 110101
printf('%032b', $int); //prints 00000000000000000000000000110101
In conclusion: leave the string as it is.
PHP intval function reference
PHP decbin function reference
Upvotes: 1
Reputation: 1062
From what I understood you want to convert any string into binary, you can do this with use of pack()
and base_convert()
$string = $_GET['YOUR_VARIABLE'];
$bin = unpack('H*', $string); // H for Hex string
$start[] = base_convert($bin[1], 16, 2); // Convert hexadecimal to binary and store it to your array
Credits of this idea goes to Francois Deschenes
Upvotes: 2