3

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.

Jachym
  • 485
  • 9
  • 21
  • 1
    do you only want to add `0b` before the string or what? – Sayed Aug 03 '15 at 15:27
  • well currently I have a code which looks like this: $start['2'] = 0b0111111110011100010011011011110; $start['3'] = 0b0111111110011100100011011011110; these are binary values and I need to create these given the user enters for example 1010011 – Jachym Aug 03 '15 at 15:30
  • 1
    Did you look at : http://stackoverflow.com/questions/6382738/convert-string-to-binary-then-back-again-using-php ? – alfallouji Aug 03 '15 at 15:32
  • Please explain more of what you want to convert from, what are the possibilities of string values? Is it only binary numbers? – Sayed Aug 03 '15 at 15:42

2 Answers2

2

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

Community
  • 1
  • 1
Sayed
  • 1,022
  • 3
  • 12
  • 27
1

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

Community
  • 1
  • 1
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48