-1

Is there a way to compute the binary representation of a decimal number, natively in Bash, without resorting to external programs such as bc?

Example: Suppose I have 5 in base 10: I want to obtain 101 in base 2.

Why using bc is not an option: loop performance.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
davide
  • 2,082
  • 3
  • 21
  • 30
  • 2
    [See this answer on linked question](http://stackoverflow.com/a/25943519/548225) – anubhava Mar 29 '15 at 17:17
  • @anubhava The question you linked doesn't specify the constrain of nativity. The answer you linked only works for numbers [0, 255] – the comment appended to that answer explains how to raise this limit, however it is pretty awkward and inefficient, so this question should be kept to collect appropriate answers. – davide Mar 29 '15 at 17:31
  • If you edit the question to clarify why using `bc` is not an option then sure this question can be opened. – anubhava Mar 29 '15 at 17:49
  • I edited the question. The concern however is not "why", but "how". – davide Mar 29 '15 at 18:35
  • 1
    What range of input values are you seeking to convert? How often are you planning to run conversions? Will you ever need to convert from binary to decimal? Is using `awk` or Perl or Python ruled out for 'loop performance'? Have you measured the performance, or are you guessing that it is a problem? What other calculations are you planning to do? But mostly — why reinvent the wheel? If using `bc` is too slow, then maybe shell is the wrong language in the first place? – Jonathan Leffler Mar 29 '15 at 19:40
  • No practical constrain on numbers range is of course preferred. Performance becomes a guesstimated concern over anything more than a thousand loop iterations: 2ms per `bc` execution gets tangible. Bash is indeed a quite-enough appropriate language (perhaps not the most one?) due to fast prototyping and easiness of system integration with the large pool of external binaries, custom and "standard" ones. – davide Mar 29 '15 at 20:08

1 Answers1

1

Use bash's arithmetic operators rather than a lookup table. For example

#!/bin/bash

d2b() {
    local bits=
    local num=$1
    while [[ $num != 0 ]]
    do
            if (( $num & 1 ))
            then
                    bits="1$bits"
            else
                    bits="0$bits"
            fi
            let num=$(($num >> 1))
    done
    echo ${bits:=0}
}

for n in $*
do
    d2b $n
done
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105