|
#!/bin/perl
my @nums=qw(01 12`b0_1 01 01b);
foreach $anum (@nums) {
print "$anum";
$anum = bin2bit($anum); print "->$anum"; print "\n";
}
my @nums=qw(91 12`d9_1 91d);
foreach $anum (@nums) {
print "$anum";
$anum = int2bit($anum); print "->$anum"; print "\n";
}
my @nums=qw(f1 12`hf_1 0xf1 F1h);
foreach $anum (@nums) {
print "$anum";
$anum = hex2int($anum); print "->$anum"; print "\n";
}
sub bin2bit {my ($bin) = @_;
$bin=~s/^[0-9]*\`b//ig; $bin=~s/_//g; $bin=~s/b$//ig;
return reverse(split('',$bin));
}
sub bit_n {my ($msb,$lsb,@bit) = @_;
while($lsb>$#bit) {push(@bit,0);}
while($msb>$#bit) {push(@bit,0);}
if( $msb eq "" ) {return @bit;}
elsif($lsb eq "" ) {return $bit[$msb];}
elsif($msb < $lsb) {return @bit[$msb..$lsb];}
else {return @bit[$lsb..$msb];}
}
sub bit2bin {return join('',reverse(@_));}
sub bit2int {my @bit = reverse(@_);
my $int=0;
while(@bit) {$int*=2; $int+=$bit[0]; shift(@bit);}
$int;
}
sub hex2int {my ($hex) = @_;
$hex=~s/^0x//ig; $hex=~s/^[0-9]*\`h//ig; $hex=~s/_//g; $hex=~s/h$//ig;
my $int=0;
my @hs=split('',$hex);
while(@hs) {
$int *=16;
if( $hs[0]=~/a/i) {$int+=10;} elsif($hs[0]=~/b/i) {$int+=11;}
elsif($hs[0]=~/c/i) {$int+=12;} elsif($hs[0]=~/d/i) {$int+=13;}
elsif($hs[0]=~/e/i) {$int+=14;} elsif($hs[0]=~/f/i) {$int+=15;}
else {$int+=$hs[0];}
shift(@hs);
}
$int;
}
sub int2bit {my ($int, $size)=@_;
$int=~s/^[0-9]*\`d//ig; $int=~s/_//g; $int=~s/d$//ig;
if($size eq "") {$size=1;}
my @bit=();
while($int >0) {push(@bit,$int&1); $int=$int>>1; $size--;}
while($size>0) {push(@bit,0); $size--;}
@bit;
}
sub int2hex {my ($int,$size)=@_;
$int=~s/^[0-9]*\`d//ig; $int=~s/_//g; $int=~s/d$//ig;
if($size eq "") {$size=1;} else {$size=(($size-1)>>2)+1;}
my @hexa=qw(0 1 2 3 4 5 6 7 8 9 A B C D E F);
my $hex="";
while($int >0) {$hex=$hexa[$int%16].$hex; $int=$int>>4; $size--;}
while($size>0) {$hex="0".$hex; $size--;}
$hex;
} |
|