Answers:
echo "obase=16; 34" | bc
如果要过滤整个整数文件,则每行一个:
( echo "obase=16" ; cat file_of_integers ) | bc
试过了printf(1)
吗?
printf "%x\n" 34
22
所有外壳中都有内置函数可以完成此操作,但是移植性较差。我尚未检查POSIX sh规格是否具有这种功能。
bc
是。例如,238862874857408875879219909679752457540
作为输入,printf给我们“结果太大”。BC方法适用于比标准int / long / bigint大的事物
printf "%X"
大写
bc
并非在所有地方都可用(至少不是在我的嵌入式Linux上)。
对不起,请尝试这个...
#!/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
printf
和hex
命令不可用。
printf
不可用?
在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
摘自zsh
docs页面上有关算术评估的示例。
我相信Bash具有类似的功能。
就我而言,我偶然发现了使用printf解决方案的一个问题:
$ printf "%x" 008
bash: printf: 008: invalid octal number
最简单的方法是将解决方案与bc一起使用,在更高版本中建议:
$ bc <<< "obase=16; 008"
8
# 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
这不是shell脚本,而是我用来在bin / oct / dec / hex之间转换数字的cli工具:
#!/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);
}