Linux shell scripts: hexadecimal to binary string

I am looking for a simple way in a shell script to convert a hexadecimal number to a sequence of 0 and 1 characters.

Example:

5F → "01011111"

Is there any command or simple method to execute it, or should I write some kind of switch for it?

+3
linux shell hex
Mar 07 '12 at 17:00
source share
5 answers

I used the bc command on Linux. (a much more complicated calculator than converting!)

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

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

Hope this helps.

+6
Mar 07 '12 at 17:12
source share
echo "ibase=16; obase=2; 5F" | bc 
+8
Mar 07 2018-12-17T00:
source share
 $ printf '\x5F' | xxd -b | cut -d' ' -f2 01011111 

or

 $ dc -e '16i2o5Fp' 1011111 
  • The i command will pull the top of the stack and use it for the input base.
  • Hex digits must be uppercase to avoid collisions with dc commands and not limited to AF if the input radius is greater than 16 .
  • The o command does the same for the output base.
  • The p command will print the top of the stack with a new line after it.
+7
Mar 07 2018-12-17T00:
source share

Perls printf already knows the binary:

 $ perl -e 'printf "%08b\n", 0x5D' 01011101 
+1
Mar 09 2018-12-12T00:
source share

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

Here is an example:

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

Productivity:

 0101111101011111010111110101111101011111 

The opposite also works.

NB: It's not perfect, and you have to work hard, but it works.

0
Nov 12 '17 at 19:47 on
source share



All Articles