在UNIX shell脚本中将十进制转换为hex

在UNIX shell脚本中,我可以使用什么将十进制数转换为hex数? 我以为od会做的伎俩,但它并没有意识到我喂它的ASCII码表示的数字。

printf的? 毛! 现在使用它,但还有什么可用?

echo "obase=16; 34" | bc 

如果要过滤整个整型文件,每行一个:

 ( echo "obase=16" ; cat file_of_integers ) | bc 

试过printf(1)

 printf "%x\n" 34 22 

在所有shell中,可能都有这样的内建函数的方法,但是它的便携性不好。 我没有检查POSIX sh规格,看它是否有这样的功能。

十六进制到十进制:

 $ echo $((0xfee10000)) 4276158464 

十进制到十六进制:

 $ printf '%x\n' 26 1a 
 bash-4.2$ printf '%x\n' 4294967295 ffffffff bash-4.2$ printf -v hex '%x' 4294967295 bash-4.2$ echo $hex ffffffff 

对不起我的错,试试这个…

 #!/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}" 

$ ./dtoh 1024

400

你在用哪种外壳? 在zsh中你可以做这样的事情:

 % typeset -i 16 y % print $(( [#8] x = 32, y = 32 )) 8#40 % print $x $y 8#40 16#20 % setopt c_bases % print $y 0x20 

(从文档中获取示例)

我相信bash也有类似的功能。

尝试:

 printf "%X\n" ${MY_NUMBER} 
 # number conversion. while `test $ans='y'` do echo "Menu" echo "1.Decimal to Hexadecimal" echo "2.Decimal to Octal" echo "3.Hexadecimal to Binary" echo "4.Octal to Binary" echo "5.Hexadecimal to Octal" echo "6.Octal to Hexadecimal" echo "7.Exit" read choice case $choice in 1) echo "Enter the decimal no." read n hex=`echo "ibase=10;obase=16;$n"|bc` echo "The hexadecimal no. is $hex" ;; 2) echo "Enter the decimal no." read n oct=`echo "ibase=10;obase=8;$n"|bc` echo "The octal no. is $oct" ;; 3) echo "Enter the hexadecimal no." read n binary=`echo "ibase=16;obase=2;$n"|bc` echo "The binary no. is $binary" ;; 4) echo "Enter the octal no." read n binary=`echo "ibase=8;obase=2;$n"|bc` echo "The binary no. is $binary" ;; 5) echo "Enter the hexadecimal no." read n oct=`echo "ibase=16;obase=8;$n"|bc` echo "The octal no. is $oct" ;; 6) echo "Enter the octal no." read n hex=`echo "ibase=8;obase=16;$n"|bc` echo "The hexadecimal no. is $hex" ;; 7) exit ;; *) echo "invalid no." ;; esac done 

就我而言,我偶然发现了一个使用printf解决方案的问题:

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

最简单的方法是使用bc解决方案,建议在后更高版本:

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