Convert decimal to hexadecimal in UNIX shell script

后端 未结 11 842
孤城傲影
孤城傲影 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: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
    

提交回复
热议问题