Skip to content

Instantly share code, notes, and snippets.

@yowcow
Last active May 7, 2016 10:09
Show Gist options
  • Save yowcow/f91c4cfc6dd0c983247a0904f8f33fd1 to your computer and use it in GitHub Desktop.
Save yowcow/f91c4cfc6dd0c983247a0904f8f33fd1 to your computer and use it in GitHub Desktop.
Binary, decimal, and hex in Perl 5
use strict;
use warnings;
use Test::More;
# See `perldoc -f pack` for documentation.
subtest 'Test unsigned char (8-bit)' => sub {
my $packed = pack('B8', '0001'.'1111');
is unpack('C', $packed), 31; # C: unsigned char
is unpack('H2', $packed), '1f';
# From: 0001 1111
# To : 1110 0000
my $complement = pack('C', ~31);
is unpack('B8', $complement), '11100000';
};
subtest 'Test unsigned short (16-bit)' => sub {
my $packed = pack('B16', '0000'.'0000'.'0001'.'1111');
is unpack('n', $packed), 31; # n: unsigned short (16-bit)
is unpack('H4', $packed), '001f';
# From: 0000 0000 0001 1111
# To : 1111 1111 1110 0000
my $complement = pack('n', ~31);
is unpack('B16', $complement), '1111111111100000';
};
subtest 'Test unsigned long (32-bit)' => sub {
my $packed = pack('B32', ('0000' x 6) . '0001'.'1111');
is unpack('N', $packed), 31; # N: unsigned long (32-bit)
is unpack('H8', $packed), '0000001f';
# From: 0000 0000 0000 0000 0000 0000 0001 1111
# To : 1111 1111 1111 1111 1111 1111 1110 0000
my $complement = pack('N', ~31);
is unpack('B32', $complement), '11111111111111111111111111100000';
};
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment