0

Okay, so I am having a bit of trouble (likely due to my ignorance) figuring this out.

$binary = base64_decode("AAAAAgYA3ncsRjy9");

So, what I have here are 12 bytes of binary data, yes?

I need to turn this into:

$binary = array("0"=>"00000000", "1"=>"00000000", "2"=>"00000000", "3"=>"00000010", "4"=>"00000110", "5"=>"00000000", "6"=>"11011110", "7"=>"01110111, "8"=>"00101100", "9"=>"01000110", "10"=>"00111100", "11"=>"10111101");

And, ultimately, drop the first 6 bytes, and split the rest into 2 byte pairs.

$binary = array("0"=>"1101111001110111", "1"=>"0010110001000110", "2"=>"0011110010111101"

Then, convert those 2 bytes chunks into base 10 decimal.

$binary = array("0"=>"56951", "1"=>"11334", "2"=>"15549");

The reason I have chose to include the actual data is because I want to make sure I am using the correct terminology. I have been trying to work with pack/unpack and have simply not been able to get this done, likely due to my not understanding the different available choices for the format argument.

I am certain I have been extremely confusing in my explanation, please accept my apologies. Any help would be greatly appreciated.


EDIT:

For posterity:

PHP Manual - function.pack

PHP Manual - function.unpack

PHP Manual - function.call-user-func-array

1 Answer 1

3

This should do it:

$binary = base64_decode("AAAAAgYA3ncsRjy9");
$binary = substr($binary, 6);
var_dump(unpack("n*", $binary));

n is unsigned short (always 16 bit, big endian byte order). With * this format is used for the entire remaining data.

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

7 Comments

Wish i could give +100 for this answer !
Absolutely wonderfully simple. A question if I may: if the binary data is simply treated as a string and thus substr is an available function why does it print/echo out as "Þw,F<½"?
@SamanthaP base64_decode returns a string and the ‘text’ you see is the characters the data corresponds to.
@Gumbo Well, thank you immensely for the prompt and very helpful answer. *Toast
@SamanthaP pack expects the values as separate arguments. You can use call_user_func_array to call a function with arguments given in an array: $bin === call_user_func_array("pack", array_merge(array("n*"), unpack("n*", $bin)))
|

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.