Linux shell scripting: hex number to binary string

2019-04-28 00:07发布

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

Example:

5F -> "01011111"

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

标签: linux shell hex
5条回答
爷的心禁止访问
2楼-- · 2019-04-28 00:23
echo "ibase=16; obase=2; 5F" | bc
查看更多
手持菜刀,她持情操
3楼-- · 2019-04-28 00:28

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

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

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

Hope it helps.

查看更多
【Aperson】
4楼-- · 2019-04-28 00:30

Perl’s printf already knows binary:

$ perl -e 'printf "%08b\n", 0x5D'
01011101
查看更多
家丑人穷心不美
5楼-- · 2019-04-28 00:39

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

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.

查看更多
Summer. ? 凉城
6楼-- · 2019-04-28 00:43
$ 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.
  • Hex digits must be in upper case to avoid collisions with dc commands and are not limited to A-F if the input radix is larger than 16.
  • The o command does the same for the output base.
  • The p command will print the top of the stack with a newline after it.
查看更多
登录 后发表回答