Linux shell 脚本:十六进制数到二进制字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9605927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:01:49  来源:igfitidea点击:

Linux shell scripting: hex number to binary string

linuxshellhex

提问by srnka

I am looking for some easy way in shell script for converting hex number into sequence of 0 and 1 characters.

我在 shell 脚本中寻找一些简单的方法来将十六进制数转换为 0 和 1 字符的序列。

Example:

例子:

5F -> "01011111"

Is there any command or easy method for accomplish it or should I write some switch for it?

是否有任何命令或简单的方法可以完成它,或者我应该为它编写一些开关吗?

采纳答案by Luchux

I used 'bc' command in Linux. (much more complex calculator than converting!)

我在 Linux 中使用了 'bc' 命令。(比转换更复杂的计算器!)

echo 'ibase=16;obase=2;5f' | bc

echo 'ibase=16;obase=2;5f' | 公元前

ibase parameter is the input base (hexa in this case), and obase the output base (binary).

ibase 参数是输入基数(在这种情况下是六进制),而 obase 是输出基数(二进制)。

Hope it helps.

希望能帮助到你。

回答by Alex Howansky

echo "ibase=16; obase=2; 5F" | bc

回答by kev

$ printf '\x5F' | xxd -b | cut -d' ' -f2
01011111

Or

或者

$ dc -e '16i2o5Fp'
1011111
  • The icommand will pop the top of the stack and use it for the input base.
  • Hexdigits must be in upper case to avoid collisions with dc commands and are not limited to A-Fif the input radix is larger than 16.
  • The ocommand does the same for the output base.
  • The pcommand will print the top of the stack with a newline after it.
  • i命令将弹出堆栈顶部并将其用作输入基数。
  • Hex数字必须大写以避免与 dc 命令冲突,并且不限于A-F输入基数大于16.
  • o命令对输出库执行相同的操作。
  • p命令将打印堆栈顶部并在其后换行。

回答by tchrist

Perl's printfalready knows binary:

Perlprintf已经知道二进制:

$ perl -e 'printf "%08b\n", 0x5D'
01011101

回答by tehmoon

I wrote https://github.com/tehmoon/cryptoclifor those kind of jobs.

我为这些工作写了https://github.com/tehmoon/cryptocli

Here's an example:

下面是一个例子:

echo -n 5f5f5f5f5f | cryptocli dd -decoders hex -encoders binary_string

Yields:

产量:

0101111101011111010111110101111101011111

The opposite also works.

反之亦然。

NB: It's not perfect and much work needs to be done but it is working.

注意:它并不完美,需要做很多工作,但它正在发挥作用。