Oct 212013
 
Article Perl

This post explains the functionality available in perl to read and write binary data, assign a value to a binary string variable, and perform the conversion of binary data to/from its decimal or hexadecimal representation.

Using the pack function to assign a binary literal to a variable

The built-in perl function pack returns a string of bytes from the decimal of hexadecimal representation received as argument.

The following sentences assign a three byte string to a variable $data, with the ASCII codes of the text string “ABC”:

The inverse of pack is ‘unpack‘. unpack returns a text string with the decimal/hexadecimal representation of  binary data received as argument:

Note: The first argument of the pack & unpack functions is a template that specifies how to perform the conversion. These functions are very flexible, and the functionality they implement is not limited to converting text strings into binary data and viceversa. There is an interesting tutorial on pack in the official Perl documentation. It explains, for instance, how to use these function to process text files with tabular information in fixed length fields..

Going through binary data with the vec function

The function “vec” can be used to read a byte in a binary string:

and it can also be used to modify a byte in a binary string:

the second argument passed to the function is the zero-based index of the byte. In the example above, the value 0x45 is assigned to the second byte (index=1) of the binary string in the $data variable.

Reading binary data from a file

In order to read binary data from a file, the read stream must be set to binary mode using the ‘binmode’ operator.

Oncde the stream has been opened in binary mode, reading is performed by succesive calls to the ‘read’ function, specifying the maximum number of bytes to read. The ‘read’ function returns the number of bytes read. The end of file is detected when the ‘read’ function returns zero.

Example:

Writing binary data to a file

The output stream must be set to binary mode in order to write binary data to a file.

Once opened for binary write, the ‘print’ function is used to write data (There exists a buil-in ‘write’ function in print, but it is not the inverse of read, as could have been expected).

Example:

First, we initialize an array to hold the 256 possible values (0..255) of a single byte:

Then we write those values to a file ‘data.out’. We do it by creating a binary string with the pack function:

The content of the binary data in the output file can be checked opening the file with a hex editor, or simply dumping the file with the xxd command:

Index of posts related to Perl programming

 Posted by at 7:45 pm

 Leave a Reply

(required)

(required)