Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know of bc:

$> var="304"
$> echo "obase=2; $var" | bc
100110000

Could it be done in shell (no external call)?

This question: Binary to hexadecimal and decimal in a shell script Asks how to convert FROM binary, not TO a binary number.

The answers there deal either with binary byte (as opposed to binary number, i.e.: a base-2 number) using xxd, or some other external tool. So, no, this question is not a duplicate of that.

share|improve this question
2  
possible duplicate of Binary to hexadecimal and decimal in a shell script – cuonglm Aug 15 '15 at 3:28
    
You should read the answer from Stéphane Chazelas, it contain all things you want. – cuonglm Aug 15 '15 at 3:49
    
Explained in the question, but it must be obvious that all answers in the question linked used external commands. None used a shell script. That is something not done before. – user79743 Aug 15 '15 at 3:50
    
All solution in that answer using shell script, it's only not POSIX. It can be better if you can stick your solution with that question. – cuonglm Aug 15 '15 at 3:54
    
That answer you link has very good points for the question asked there. And solves some parts of the problem only for ksh and/or zsh. There is no solution usable in bash, for example. Even worse, there is no attempt to make a portable solution. – user79743 Aug 15 '15 at 4:05

In bash:

toBinary(){
    local n bit
    for (( n=$1 ; n>0 ; n >>= 1 )); do  bit="$(( n&1 ))$bit"; done
    printf "%s\n" "$bit"
}

Use:

$> toBinary 304
100110000

Or more POSIX_ly:

toBinaryPOSIX(){
    n="$1"
    bit="" 
    while [ "$n" -gt 0 ]; do
        bit="$(( n&1 ))$bit";
        : $(( n >>= 1 ))
    done
    printf "%s\n" "$bit"
}

Use:

$> toBinaryPOSIX 304
100110000

If Value is hex:

$> toBinaryPOSIX "$(( 0x63 ))"
1100011
share|improve this answer
    
local is not in POSIX. – cuonglm Aug 15 '15 at 2:47
    
Ooops. Done, I hope. – user79743 Aug 15 '15 at 3:10

perl is good tool for this job:

$ var="304"
$ perl -e 'printf "%b\n",'$var
100110000
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.