Sunday, March 13, 2011

Perl pack/unpack notes

Original post

'b' and 'B' formats


The 'b' and 'B' formats pack strings consisting of '0' and '1' characters to bytes and unpack bytes to strings of '0' and '1' characters. Perl treats even valued characters as 0 and odd valued characters as 1 while packing. The difference between the two is the order of the bits within each byte. With 'b', the bits are specified in increasing order. With 'B', in descending order. The count represents the number of bits to pack.

Examples

ord(pack('b8','00100110')) produces 100 (4 + 32 + 64)
ord(pack('B8','00100110')) produces 38 (32 + 4 + 2)

Here "Increasing Order" means from LSB to MSB, "Descending Order" means from MSB to LSB.

'h' and 'H' formats


The 'h' and 'H' formats pack strings containing hexadecimal digits. 'h' takes the low nybble first, 'H' takes the high nybble first. The count represents the number of nybbles to pack. In case you were wondering, a nybble is half a byte.

Examples

Each of the following returns a two byte scalar.
pack('h4','1234') produces 0x21,0x43
pack('H4','1234') produces 0x12,0x34

No comments:

Post a Comment