Back to Top

How To Store Binary Data in PHP

Here is one more quick article about to store binary data in strings with the use of two core functions in PHP.

Like, You want to parse a string that have values encoded as a binary structure or want to encode values into a string.Let’s see an example that you want to store numbers in the binary representation instead of sequences of ASCII characters.so you need to use the pack() function to store binary data in a string.

What is pack() method?

pack() method is mainly used to store the data in binary form in PHP

The first argument into a pack() function is the format as a string which shows how to encode the data and other passed arguments are the data we want to pack as the binary string. The s3 format produces the three unsigned short 16-bit numbers in the byte as the order from its input data.Given input 1994,54,225 returns eight bytes

What is unpack() function?

unpack() transforms binary data into an associative array based on the format.

Syntax

Here, Format parameter is used when unpacking and binary_string is used to unpack Binary string.This function parses a binary string according to a user-defined format.

Returns:

It returns an associative array and FALSE on error.

Now, Let’s see unpack() function

unpack() function SYNTAX

The first argument into an unpack() function is also a format as a string and second argument is encoded data that you want to decode.and the output of the unpack() function will be a decoded data as associative array.

OUTPUT

You can use different format characters and their count can be followed by an array key in unpack() function.

Example:

OUTPUT

Even you can use multiple formats and can separate them by a slash / with unpack() function.You can also use unpack( ) as a substitute for substr( ) method to extract fields.Both substr( ) and unpack( ) function have equivalent capabilities when the fixed-width fields but unpack( ) is the better solution when the elements of the fields aren’t just strings.

Example:

OUTPUT

There are many format characters that can be used with the pack( ) and unpack( ) function. you can see format character in PHP Manual. Do you have any question about pack() and unpack() function? Let me know in comment section.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to Create and Use Cookies in PHP

Posted on 7 years ago

Bhumi

Post via e-mail in WordPress

Posted on 12 years ago

Bhumi

How to use JavaScript Promise API?

Posted on 6 years ago

Bhumi

What is Closure in JavaScript?

Posted on 6 years ago

Bhumi