0

Is there any native method that converts an unsigned integer to a binary string (either big-endian order or little-endian order is okay). The current way I come up with is:

$n = 0x12345678;
$s = "";
for ($i = 0; $i < 4; $i++)
{
    //For big-endian: $s[$i] = chr(($n >> 8 * (4 - 1 - $i)) & 0xff);
    $s[$i] = chr(($n >> 8 * $i) & 0xff);
}

But these are not performant, I wonder if there is some native method that does the job. But I haven't found any for now.

4
  • 1
    php.net/manual/en/function.decbin.php Commented Mar 8, 2021 at 5:05
  • decbin is not the right method, it converts an integer to a textual binary string. I mean an actual binary string, not a textual binary string (See the title of the question). Commented Mar 8, 2021 at 5:08
  • Unbale to understand the difference between actual binary string and textual binary string Commented Mar 8, 2021 at 5:32
  • Understand and run my code, and then var_dump($s). And then run var_dump(decbin($n));. Commented Mar 8, 2021 at 5:43

1 Answer 1

1

After some search, I found two ways to achieve this:

The better of the two slutions, that I am going to use:

$n = 0x12345678;
//For big-endian: var_dump(pack('N', $n));
var_dump(pack('V', $n));

and suboptimally:

$n = 0x12345678;
//This only supports big-endian.
var_dump(hex2bin(dechex($n)));
Sign up to request clarification or add additional context in comments.

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.