and then a binary number echo Usage: 10101 } #Is a function to the search if a string has..." /> and then a binary number echo Usage: 10101 } #Is a function to the search if a string has..." />

Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BASH binary to decimal
01-11-2010, 01:46 PM (This post was last modified: 01-11-2010 02:43 PM by codecaine.)
Post: #1
BASH binary to decimal
I attached my source in a zip
Code:
#!/bin/bash


usage()
{
    #echos program name which is $0 and then a binary number
    echo "Usage: $0 10101"
}

#Is a function to the search if a string has nothing but 1 & 0's. Returns 0 for true and 1 if false
isBinary()
{
    #by default bash varaibles are gobal if you declare a varible with local is then it becomes local
    local binaryStr=`echo "$1" | sed -n '/^[0-1]*$/p'`
    if [ -z $binaryStr ]
    then
        return 1
    else
        return 0
    fi
}

#check if binary
isBinary $1

if [ $# -gt 0 ]
then
    #check if the user entered a binary number
    if  isBinary $1
    then
        #specail varible for math operations $((expression in here)) 2# is for base you could do echo $((3*3)) will show 9
        echo "$((2#$1))"
    else
        echo "invalid binary number enter"
        usage
        exit 1
    fi
else
    usage
fi


Attached File(s)
.zip  bin2dec.zip (Size: 986 bytes / Downloads: 0)
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: