Convert bytes to binary


I’m using this function
and i would to convert this random bytes to a binary view.

I’ve tried to convert it to hex2bin and then i used to function pack to convert it to a binary but it doesn’t work.

How can convert a random bytes to a binary ?


random_bytes returns binary data, but not in a readable format. If you want to actually represent it as a string of 1s and 0s, you’ll need to first convert it using one of PHP’s bin2* functions, then use base_convert to convert it back:

function random_binary($bytes) {
  return base_convert(bin2hex(random_bytes($bytes)), 16, 2);

echo random_binary(1);

// 10000011

This will only work up to the system’s integer limit (likely 2^63-1 on a 64-bit system). If you’ve got the GMP extension installed, you can use the following for arbitrary precision:

function random_binary($bytes) {
  $hex = bin2hex(random_bytes($bytes));
  return gmp_strval(gmp_init($hex, 16), 2);

echo random_binary(40);

// 10000000101110000010011111001011011100111110...

Answered By – iainn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published