3

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?

3
  • 2
    The answer would depend on whether this is actually an IPv6 address, in which case your example can also be written as 2001:0db8:3c4d:0015::abcd:ef12. But either way, this isn't hard to do yourself. Do you know pack 'H*'? Commented Nov 5, 2013 at 7:42
  • @amon Yes, it is an IPv6 address Commented Nov 5, 2013 at 8:44
  • @amon Please have a look at the edit Commented Nov 5, 2013 at 8:56

1 Answer 1

6
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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.