Converting from base 8 to base 2
--------------------------------
::
In article ,
Dan Peterson wrote:
>How can I easily, tersely, cleverly convert from base 8 (octal) to base 2
>(binary)?
>
>I'd like to take an octal number (a file mode) and create an array of 0/1
>values that represent the individual permission bits. In other words the
>following examples:
The reason computer people use octal at all, is that 1 octal digit
is 3 binary digits. (Similarly, 1 hexadecimal digit is 4 binary
digits.) So you can simply convert each octal digit to the
corresponding 3 binary digits, and vice versa, using Perl's s///eg
construct.
I've changed the specification slightly to use scalars for both
inputs and outputs: you can easily use split or join to convert
them to or from arrays.
@o2b = (qw/000 001 010 011 100 101 110 111/);
sub o2b {
my($v) = @_;
$v =~ s/([0-7])/$o2b[$1]/eg;
return $v;
}
%b2o = (qw/000 0 001 1 010 2 011 3 100 4 101 5 110 6 111 7/);
sub b2o {
my($v) = $_;
# Pad the binary string to a multiple of 3.
$v = '0' . $v while length($v) % 3;
$v =~ s/([01]{3})/$b2o{$1}/eg;
return $v;
}
Tim.
--
Tim Goodwin | "Forget the mystical level numbers." -- Henry Spencer
Original headers::
From: tim@pipex.net (Tim Goodwin)
Newsgroups: comp.lang.perl.misc
Subject: Re: Converting from base 8 to base 2
Date: 2 Feb 1996 13:52:25 GMT
Organization: Unipalm PIPEX
Message-ID: <4et4up$m0c@wave.news.pipex.net>
References: