Convert decimal to hexadecimal in UNIX shell scrip

2020-01-25 04:40发布

In a UNIX shell script, what can I use to convert decimal numbers into hexadecimal? I thought od would do the trick, but it's not realizing I'm feeding it ASCII representations of numbers.

printf? Gross! Using it for now, but what else is available?

标签: unix shell hex
11条回答
叼着烟拽天下
2楼-- · 2020-01-25 05:34
echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc
查看更多
叛逆
3楼-- · 2020-01-25 05:35

Hexidecimal to decimal:

$ echo $((0xfee10000))
4276158464

Decimal to hexadecimal:

$ printf '%x\n' 26
1a
查看更多
老娘就宠你
4楼-- · 2020-01-25 05:35
bash-4.2$ printf '%x\n' 4294967295
ffffffff

bash-4.2$ printf -v hex '%x' 4294967295
bash-4.2$ echo $hex
ffffffff
查看更多
老娘就宠你
5楼-- · 2020-01-25 05:36

This is not a shell script, but it is the cli tool I'm using to convert numbers among bin/oct/dec/hex:

    #!/usr/bin/perl

    if (@ARGV < 2) {
      printf("Convert numbers among bin/oct/dec/hex\n");
      printf("\nUsage: base b/o/d/x num num2 ... \n");
      exit;
    }

    for ($i=1; $i<@ARGV; $i++) {
      if ($ARGV[0] eq "b") {
                    $num = oct("0b$ARGV[$i]");
      } elsif ($ARGV[0] eq "o") {
                    $num = oct($ARGV[$i]);
      } elsif ($ARGV[0] eq "d") {
                    $num = $ARGV[$i];
      } elsif ($ARGV[0] eq "h") {
                    $num = hex($ARGV[$i]);
      } else {
                    printf("Usage: base b/o/d/x num num2 ... \n");
                    exit;
      }
      printf("0x%x = 0d%d = 0%o = 0b%b\n", $num, $num, $num, $num);
    }
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-01-25 05:38

Tried printf(1)?

printf "%x\n" 34
22

There are probably ways of doing that with builtin functions in all shells but it would be less portable. I've not checked the POSIX sh specs to see whether it has such capabilities.

查看更多
登录 后发表回答