1

How do I convert the string 01100110 01101111 01101111 to foo in Unix? Which of the GNU Core Utilities does that if any? I know how to do it in Python, but it must be possible with another tool, no? The tools hexdump and od don't seem to do the trick.

This tool does what I want: http://www.unit-conversion.info/texttools/convert-text-to-binary/

tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108

1 Answers1

2

Using printf built-in and bash:

for x in 01100110 01101111 01101111; do printf "%b" $(printf '\\x%x' $((2#$x))); done; echo

results in foo as expected. Breakdown:

  1. $((2#$x)) converts what's in 'x' from binary to decimal.
  2. the \\x%x converts the decimal to hexa, add adding a \x at the beginning so the next printf sees it and treats it like an hexa.
  3. %b printf - print hexa as character.
kabanus
  • 24,623
  • 6
  • 41
  • 74
  • 1
    for performance passing through variable assignment avoids launching a sub shell : `printf -v x %x $((2#$x)); printf '\x'$x;` and it's much faster – Nahuel Fouilleul Jun 15 '17 at 12:10
  • an example to compare `time { for ((i=0;i<100;i+=1)); do printf -v x %x $((2#01010101)); printf '\x'$x; done; echo; }` and `time { for ((i=0;i<100;i+=1)); do printf "%b" $(printf '\\x%x' $((2#01010101))); done; echo; }` – Nahuel Fouilleul Jun 15 '17 at 12:17