Skip to content

Instantly share code, notes, and snippets.

@c02y
Last active August 26, 2018 10:32
Show Gist options
  • Save c02y/7f933d17ea1d414f99fb67d155ac223d to your computer and use it in GitHub Desktop.
Save c02y/7f933d17ea1d414f99fb67d155ac223d to your computer and use it in GitHub Desktop.
one base converter for all bin/oct/dec/hex
#!/usr/bin/perl
if (@ARGV < 2) {
printf("Convert numbers among bin/oct/dec/hex\n");
printf("\nUsage: b2 2/8/10/16 num num2 ... \n");
exit;
}
for ($i=1; $i<@ARGV; $i++) {
if ($ARGV[0] == 2) {
$num = oct("0b$ARGV[$i]");
} elsif ($ARGV[0] == 8) {
$num = oct($ARGV[$i]);
} elsif ($ARGV[0] == 10) {
$num = $ARGV[$i];
} elsif ($ARGV[0] == 16) {
$num = hex($ARGV[$i]);
} else {
printf("Usage: b2 2/8/10/16 num num2 ... \n");
exit;
}
printf("0x%x = 0d%d = 0%o = 0b%b\n", $num, $num, $num, $num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment