Converting hexadecimal string to binary

Prats picture Prats · Nov 5, 2013 · Viewed 7.6k times · Source

I am having following hexadecimal address : 2001:0db8:3c4d:0015:0000:0000:abcd:ef12. There are 8 blocks of hexadecimal digits, each block is 16 bits long, total 128-bits. I want to convert each of these blocks into binary, i.e if I take the 1st block - 2001, than I want to convert it to binary and than take the 2nd block - 0db8, convert it to binary and so on.....

Likewise I need to iterate through each block, convert them to binary and then pack them.

Can anyone tell me the most simplest way in which I can achieve it?

Answer

jkshah picture jkshah · Nov 5, 2013
my $str = '2001:0db8:3c4d:0015:0000:0000:abcd:ef12';
print  join "\n", map { unpack ('B*', pack ('H*',$_)) } split ':', $str;

Output:

0010000000000001
0000110110111000
0011110001001101
0000000000010101
0000000000000000
0000000000000000
1010101111001101
1110111100010010

EDIT

Following lines are culprit in your code. Try removing them.

my $tempbin1 = pack( 's', $elements[0]);
my $tempbin2 = pack( 's', $elements[1]);