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.

4
  • 1
    do you only want to add 0b before the string or what? Commented Aug 3, 2015 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 Commented Aug 3, 2015 at 15:30
  • 1
    Did you look at : stackoverflow.com/questions/6382738/… ? Commented Aug 3, 2015 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? Commented Aug 3, 2015 at 15:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.