1

I have a string for example: "10001000101010001" in PHP I am compressing it with gzcompress, but it compresses ASCII equivalent. I would like to compress the string as if it were binary data not it ASCII binary equivalent.

Bascially I have 2 problems:

  1. how to convert a list of 1s and 0s into binary
  2. compress the resulting binary with gzcompress

thanks in advance.

1
  • Maybe you could write your "binary" string into a file and call gzfile(). Commented Jul 10, 2011 at 15:06

1 Answer 1

3

Take a look at the bindec() function.

Basically you'll want something like (dry-coded, please test it yourself before blindly trusting it)

function binaryStringToBytes($binaryString) {
    $output = '';
    for($i = 0; $i < strlen($binaryString); $i += 8) {
        $output .= chr(bindec(substr($binaryString, $i, 8)));
    }
    return $output;
}

to turn a string of the format you specified into a byte string, after which you can gzcompress() it at will.

The complementary function is something like

function bytesToBinaryString($byteString) {
    $out = '';
    for($i = 0; $i < strlen($byteString); $i++) {
        $out .= str_pad(decbin(ord($byteString[$i])), 8, '0', STR_PAD_LEFT);
    }
    return $out;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @AKX! thanks for your help. So therefore can I do this? $output = ''; for($i = 0; $i < strlen($string_to_compress); $i += 8) { $output .= chr(bindec(substr($string_to_compress, $i, 8))); } gzcompress($bin_output_comp, 7);
You could just use those functions as-is in your source and then simply do $compressed = gzcompress(binaryStringToBytes('10001000101010001'), 7);.

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.