張俊芝
張俊芝

Reputation: 387

[PHP]native method to convert an unsigned integer to a binary string (not textual binary string)

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.

Upvotes: 0

Views: 105

Answers (1)

張俊芝
張俊芝

Reputation: 387

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)));

Upvotes: 1

Related Questions