DelphiFAQ Home Search:
General :: Programming :: perl
General questions about perl.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.
Recommended links on this topic:
Featured Article

How do I convert bits into ints?

Question:

How can I convert a number from binary format (0 and 1) to decimal?

Answer:

You need to use pack() the data to an eight bit binary structure then unpack it to the desired target structure with unpack() - or if the target is decimal, you can use ord().

A few words on pack(). This function is very useful when processing CGI posted data, since this is often escaped. The first argument in pack() is a template. There are quite a few values - for a full documentation look here: http://www.perldoc.com/perl5.6.1/pod/func/pack.html

# convert from binary to decimal
 $decimal = unpack('c', pack('B8', '10110110'));  
 
 # same functionality but using ord()
 $decimal = ord(pack('B8', '10110110'));
 
 # from hex to binary
 $binary_string = unpack('B', "\x41");  
 
 
 # unescaping CGI data
 $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($value))/eg;
 

Generated 16:02:02 on Dec 14, 2017