简体   繁体   English

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

[英]Linux shell scripting: hex number to binary string

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? 是否有任何命令或简单的方法来完成它或我应该为它写一些开关?

echo "ibase=16; obase=2; 5F" | bc
$ printf '\x5F' | xxd -b | cut -d' ' -f2
01011111

Or 要么

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

I used 'bc' command in Linux. 我在Linux中使用'bc'命令。 (much more complex calculator than converting!) (比转换更复杂的计算器!)

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

ibase parameter is the input base (hexa in this case), and obase the output base (binary). ibase参数是输入基数(在本例中为hexa),并且取消输出基数(二进制)。

Hope it helps. 希望能帮助到你。

Perl's printf already knows binary: Perl的printf已经知道二进制:

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

I wrote https://github.com/tehmoon/cryptocli for 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. 注意:它并不完美,还有很多工作要做,但它确实有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM