我正在尝试将 32 个字符长的十六进制字符串(例如:A41EB86E184207262C12F66E7C480577
)转换为二进制。我正在使用:
echo "ibase=16; obase=2; $line" | bc
但它之间包含不必要的 \
,这不允许我对结果执行任何位操作。
我得到的示例输出是:
10100100000111101011100001101110000110000100001000000111001001100010\
110000010010111101100110111001111100010010000000010101110111
注意第一行末尾的 \
。
我该怎么做才能避免这种情况?
最佳答案
如果您有足够现代的 bc
,您可以将 BC_LINE_LENGTH
设置为零以禁用换行:
pax> echo "ibase=16;
...> obase=2;
...> A41EB86E184207262C12F66E7C480577" | BC_LINE_LENGTH=0 bc
这会在一行上输出您的号码。
1010010000011110101110000110111000011000010000100000011100100110001011000001...
我倾向于将其放在我的 .profile
(或 .bashrc
,我记不清了)中,因为我喜欢将其作为默认:
export BC_LINE_LENGTH=0
来自联机帮助页:
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.
如果您的 bc
不支持“0 表示禁用”扩展,您也可以将其设置得高得离谱:
export BC_LINE_LENGTH=9999
如果您的 bc
受到“挑战”,因为它根本不允许 BC_LINE_LENGTH
,您可能需要恢复到输出的后处理,例如使用 tr
去除换行符和反斜杠:
pax> echo "ibase=16;obase=2;A41EB86E184207262C12F66E7C480577" | bc | tr -d '\\\n'
关于bash - bc 中的大型十六进制到二进制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633199/