【问题标题】:hexadecimal to decimal conversion in bashbash中的十六进制到十进制转换
【发布时间】:2019-05-10 17:38:22
【问题描述】:

我在互联网上查找了我的问题,但找不到答案。抱歉,如果之前回答过。这是为 bash 准备的。

所以我的脚本将读取一个 input.dat 文件,并查看行并根据它进行算术运算。示例:

#input.dat file:
205 - 12
0xFED - 0xABCD

使用代码echo $((p)) 其中 p 是循环计数(帮助我计算和打印每一行)但 0xFED - 0xABCD 返回 -39904 ,但我希望它返回其十六进制对应项。

./test.sh input.dat

while read p; do
echo $((p))
done <$1

返回:

193
-39905

但我希望它返回一个十六进制结果而不是十进制,如果计算是在十六进制值上完成的。

欢迎提出任何想法!

【问题讨论】:

  • 请在您的问题中添加示例输入和该示例输入所需的输出。
  • 编辑澄清!
  • 对于这个特殊问题,Bash 看起来是个糟糕的选择。 Perl 或 Python 应该是微不足道的; awk 也不应该太难。
  • 如果您输入了0xa - 1010 - 10 怎么办?第一个应该是十六进制还是十进制?

标签: linux bash


【解决方案1】:

使用printf 指定应如何打印输出。对于十六进制表示您可以使用%x printf 修饰符,对于十进制表示您可以使用%d printf 修饰符。

不要复制下面的代码,它会尝试删除驱动器上的所有文件。下面代码中的注释:

# for each line in input
# with leading and trailing whitespaces removed
while IFS=$' \r\n' read -r line; do 

    # ADD HERE: tokenization of line
    # checking if it's valid and safe arithmetic expression

    # run the arithemetical expansion on the line fetching the result
    # this is extremely unsafe, equal to evil eval
    if ! res=$((line)); then
        echo "Arithmetical expansion on '$p' failed!"
        exit 1
    fi

    # check if the line starts with `0x`
    # leading whitespaces are removed, so we can just strip the leading two character
    if [ "${p:0:2}" == "0x" ]; then
        # if it does print the result as a hexadecimal
        printf "%x\n" "$res" 
    else
        printf "%d\n" "$res"
    fi

# use heredoc for testing input
done <<EOF
205 - 12
0xFED - 0xABCD
0 $(echo "I can run any malicious command from here! Let's remove all your files!" >&2; echo rm -rf / )
EOF

【讨论】:

  • 是的,人们不应该在可能包含$( ... ; rm ... ; ) 的输入中使用while read。与其包含实际的破坏性代码,为什么不吓唬他们,而只是在你的顽皮命令前附加echo
猜你喜欢
  • 2020-09-25
  • 1970-01-01
  • 2017-05-05
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 2023-04-01
相关资源
最近更新 更多