Convert decimal to hexadecimal in UNIX shell script

后端 未结 11 786
孤城傲影
孤城傲影 2020-11-29 19:08

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 represent

相关标签:
11条回答
  • 2020-11-29 19:11

    In my case, I stumbled upon one issue with using printf solution:

    $ printf "%x" 008 bash: printf: 008: invalid octal number

    The easiest way was to use solution with bc, suggested in post higher:

    $ bc <<< "obase=16; 008" 8

    0 讨论(0)
  • 2020-11-29 19:12
    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
    
    0 讨论(0)
  • 2020-11-29 19:15

    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);
        }
    
    0 讨论(0)
  • 2020-11-29 19:17

    Try:

    printf "%X\n" ${MY_NUMBER}
    
    0 讨论(0)
  • 2020-11-29 19:20

    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.

    0 讨论(0)
  • 2020-11-29 19:24

    Sorry my fault, try this...

    #!/bin/bash
    :
    
    declare -r HEX_DIGITS="0123456789ABCDEF"
    
    dec_value=$1
    hex_value=""
    
    until [ $dec_value == 0 ]; do
    
        rem_value=$((dec_value % 16))
        dec_value=$((dec_value / 16))
    
        hex_digit=${HEX_DIGITS:$rem_value:1}
    
        hex_value="${hex_digit}${hex_value}"
    
    done
    
    echo -e "${hex_value}"
    

    Example:

    $ ./dtoh 1024
    400
    
    0 讨论(0)
提交回复
热议问题