首页 文章

bash中的十六进制到十进制转换

提问于
浏览
-3

我在互联网上查找了我的问题,但找不到答案 . 如果以前回答过,请道歉 . 这是为了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

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

欢迎任何想法!

1 回答

  • 0

    使用 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
    

相关问题