[Pdx-pm] bit conversion brain-teaser

Joshua Hoblitt jhoblitt at ifa.hawaii.edu
Tue Mar 4 18:56:39 CST 2003

> How about something like this?:
> #!/usr/bin/perl -w
> use strict;
> my $hex = '6';
> my $bin = sprintf("%b", $hex);
> print "bin is: $bin\nhex is: $hex\n";

Your close but "%b" is expecting a binary int.  So you need to add a hex -> decimal conversion so perl will store the value internaly as an int.  Your example works because the number 6 is already in decimal (and has the same value as 0x6). It however wouldn't work with any hex value > 0x9.

my $hex = hex( '7F' );
# -OR-
my $hex = 0x7F;

my $bin = sprintf("%b", $hex);

print "bin is: $bin\n";

Good idea.



More information about the Pdx-pm-list mailing list