1

So I made a decimal to binary converter but currently it doesn't chop off the zeros in the beginning. If I entered 64 for $1 it would start with 13 zeros which is rather unsightly but I don't know how to chop them off. Any help?

#!/bin/bash

cat /dev/null > ~/Documents/.tobinary
touch ~/Documents/.tobinary

toBin=$1
counter=0
numZeros=0
first1=0
kill=0
echo $toBin

for v in {19..0}
do
    let temp=2**$v
    let test=$toBin-$temp

    if [ $test -ge 0 ]
    then
            if [ $first1 -eq 0 ]
            then
                    kill=$numZeros
                    let first1++
            fi
            if [ $test -gt 0 ]
            then
                    echo -n 1 >> ~/Documents/.tobinary
                    toBin=$test
            elif [ $test -eq 0 ]
            then
                    echo -n 1 >> ~/Documents/.tobinary
                    while [ $counter -lt $v ]
                    do
                        echo -n 0 >> ~/Documents/.tobinary
                            let counter++
                    done
                    break
            fi
    elif [ $test -lt 0 ]
    then
            echo -n 0 >> ~/Documents/.tobinary
            let numZeros++
    fi
done

cat ~/Documents/.tobinary
  • 1
    Is there a strong reason against using bc (with obase=2)? – Ralph Rönnquist Oct 1 '16 at 6:07
  • This look like self training purpose, you can "see" all execution using set -x in first line, you might whish to reduce wideness (e.g. {5-0} instead of {19-0}). Real unixan do use echo and set -x when debugging. – Archemar Oct 1 '16 at 6:59
  • 2
    sed '1s/^0*//' file? – Cyrus Oct 1 '16 at 7:18
0

Is there a specific reason for which you used this particular algorithm?

I'd rather construct the binary in shell variables than in a file. In such case you can strip the leading zeroes by adding a zero to a number, such as

expr 00001111 + 0
1111

Also, if you have to use a file, I would suggest using /tmp instead of ~/Documents to hold temporary files. And finally, if I were you, I would prefer to construct the binary using a divide method, which naturally ends when the conversion is completed, thus avoiding the problem of leading zeroes rather than solving it.

  • How would I construct the binary in a shell variable. As a string? Would I replace the 'echo -n 1 >> ~/Documents/.tobinary' with 'answer="$answer"+"1"'? – J. Doe Oct 4 '16 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.