从十六进制转换为二进制数时出现意外的反斜杠

从十六进制转换为二进制数时出现意外的反斜杠

我正在尝试将十六进制行转换为二进制bash,但输出包含反斜杠。有人可以解释为什么吗?

输入:

for i in 3D3D516343746D4D6D6C315669563362; do BIN=$(echo "ibase=16; obase=2; $i" | bc); echo $BIN; done

输出:

11110100111101010100010110001101000011011101000110110101001101011011\ 0101101100001100010101011001101001010101100011001101100010

答案1

POSIX 的实现bc将输出行分割为最多 70 个字符,使用反斜杠作为行继续符

如果您有 GNU 版本bc,您可以使用环境变量覆盖此行为BC_LINE_LENGTH,例如

$ printf 'ibase=16; obase=2; %s\n' 3D3D516343746D4D6D6C315669563362 | BC_LINE_LENGTH=0 bc
111101001111010101000101100011010000110111010001101101010011010110110101101100001100010101011001101001010101100011001101100010

info bc

'BC_LINE_LENGTH'
     This should be an integer specifying the number of characters in an
     output line for numbers.  This includes the backslash and newline
     characters for long numbers.  As an extension, the value of zero
     disables the multi-line feature.  Any other value of this variable
     that is less than 3 sets the line length to 70.

答案2

您可以使用一些“bashisms”过滤输出:echo ${BIN//[$'\r\n\\']}

例子:

for i in 3D3D516343746D4D6D6C315669563362; do BIN=$(echo "ibase=16; obase=2; $i" | bc); echo ${BIN//[$'\r\n\\']};done

您还可以使用 env 变量BC_LINE_LENGTH,GNU bc 将使用该变量来调整行长度(0 是无限的)。

例子:

for i in 3D3D516343746D4D6D6C315669563362; do BIN=$(echo "ibase=16; obase=2; $i" | BC_LINE_LENGTH=0 bc ); echo $BIN;done

答案3

如果GNU bc不可用,这也有效:

echo "ibase=16; obase=2; 3D3D516343746D4D6D6C315669563362" | \
    bc | tr -d '\\\n' ; echo
111101001111010101000101100011010000110111010001101101010011010110110101101100001100010101011001101001010101100011001101100010

(故意不包装太长的输出。)

相关内容