8

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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
srnka
  • 1,275
  • 2
  • 12
  • 16

5 Answers5

12
echo "ibase=16; obase=2; 5F" | bc
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • Thanks, it is the same as my selected correct answer, I've chosen it since there is explanation – srnka Mar 12 '12 at 15:53
  • 4
    This is not the same as the selected answer. This has `5F`, whereas the selected answer has `5f`. This answer works in `bc` 1.06.95, wheras the selected answer does not. – nrz Apr 24 '17 at 16:28
10

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.

Luchux
  • 803
  • 1
  • 7
  • 17
  • 2
    Set `obase` before `ibase`. If `ibase` is defined first, `bc` will try to interpret `obase` as if it is written in `ibase`, with possibly erroneous results. See [this question](http://stackoverflow.com/questions/9889839/bc-and-its-ibase-obase-options). – mcmlxxxvi Feb 06 '14 at 10:11
  • 4
    Using`bc` version 1.06.95 `echo 'ibase=16;obase=2;5f' | bc` produces error: `(standard_in) 1: syntax error`. However, `echo 'ibase=16;obase=2;5F' | bc` works and produces `1011111`. – nrz Apr 24 '17 at 16:25
8
$ 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.
kev
  • 155,172
  • 47
  • 273
  • 272
  • Thanks for response, it's great to have so many ways of achieving this task :) I've chosen the "bc" variant – srnka Mar 12 '12 at 15:53
2

Perl’s printf already knows binary:

$ perl -e 'printf "%08b\n", 0x5D'
01011101
tchrist
  • 78,834
  • 30
  • 123
  • 180
1

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.

tehmoon
  • 567
  • 4
  • 8