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

fra*_*man 9 binary bash hex bc

我正在尝试使用bash将一系列字节从十六进制转换为二进制.但我一直得到(看似随机)"(standard_in)1:语法错误"回复以下代码:

for j in c4 97 91 8c 85 87 c4 90 8c 8d 9a 83 81
do
        BIN=$(echo "obase=2; ibase=16; $j" | bc )
        echo $BIN
done
Run Code Online (Sandbox Code Playgroud)

我做了一个与dec to bin类似的东西,它完美地工作:

for i in {0..120}
do
        KEYBIN=$(echo "obase=2; ibase=10; $i" | bc)
        echo $KEYBIN
done
Run Code Online (Sandbox Code Playgroud)

有没有人知道为什么它适用于十进制,但不是十六进制?在我看来,语法几乎相同(除非我遗漏了一些非常难的东西.)

Fre*_*ihl 16

BC对十六进制值的情况有点敏感,更改为大写,它应该工作

for j in C4 97 91 8C 85 87 C4 90 8C 8D 9A 83 81
do
        BIN=$(echo "obase=2; ibase=16; $j" | bc )
        echo $BIN
done
Run Code Online (Sandbox Code Playgroud)

输出:

11000100
10010111
10010001
10001100
10000101
10000111
11000100
10010000
10001100
10001101
10011010
10000011
10000001
Run Code Online (Sandbox Code Playgroud)


stu*_*stu 15

我想出了这个:

printf 转换为十六进制,xxd -r -p 获取 ascii 十六进制流并使其成为实际的二进制文件

使用 hexdump 转储以证明它有效...

printf "%016x" 53687091200 | xxd -r -p | hexdump -C
Run Code Online (Sandbox Code Playgroud)


Spe*_*bun 7

这是我使用的脚本:

#!/bin/bash
# SCRIPT:  hex2binary.sh
# USAGE:   hex2binary.sh Hex_Number(s)
# PURPOSE: Hex to Binary Conversion. Takes input as command line
#          arguments.
#####################################################################
#                      Script Starts Here                           #
#####################################################################

if [ $# -eq 0 ]
then
    echo "Argument(s) not supplied "
    echo "Usage: hex2binary.sh hex_number(s)"
else
    echo -e "\033[1mHEX                 \t\t BINARY\033[0m"

    while [ $# -ne 0 ]
    do
        DecNum=`printf "%d" $1`
        Binary=
        Number=$DecNum

        while [ $DecNum -ne 0 ]
        do
            Bit=$(expr $DecNum % 2)
            Binary=$Bit$Binary
            DecNum=$(expr $DecNum / 2)
        done

        echo -e "$Number              \t\t $Binary"
        shift
        # Shifts command line arguments one step.Now $1 holds second argument
        unset Binary
    done

fi
Run Code Online (Sandbox Code Playgroud)