Pages

Monday, December 20, 2010

Decimal to Binary Conversion Shell Script


#!/bin/bash
# SCRIPT: dec2binary.sh
# USAGE: dec2binary.sh Decimal_Number(s)
# PURPOSE: Decimal to Binary Conversion. Takes input as command line
# arguments.
# \\\\ ////
# \\ - - //
# @ @
# ---oOOo-( )-oOOo---
#
#####################################################################
# Script Starts Here #
#####################################################################

if [ $# -eq 0 ]
then
echo "Argument(s) not supplied "
echo "Usage: dec2binary.sh Decimal_number(s)"
else
echo -e "\033[1mDECIMAL \t\t BINARY\033[0m"

while [ $# -ne 0 ]
do
DecNum=$1
Binary=
Number=$DecNum

while [ $DecNum -ne 0 ]
do
Bit=$(expr $DecNum % 2)
Binary=$Bit$Binary
DecNum=$(expr $DecNum / 2)
done

echo -e "$Number \t\t $Binary"
shift
# Shifts command line arguments one step.Now $1 holds second argument
unset Binary
done

fi

#NOTE: Using bc command you can directly get output at command line.
# $ echo 'obase=2;15' | bc
# 1111
# $ echo 'obase=2;1023' | bc
# 1111111111
# $ echo 'obase=2;1024' | bc
# 10000000000
# No need of ibase=10, because default ibase is 10.

OUTPUT:
# sh dec2binary.sh 7 16 255 256 1023 1024
DECIMAL BINARY
7 111
16 10000
255 11111111
256 100000000
1023 1111111111
1024 10000000000

# sh dec2binary.sh 9223372036854775807
DECIMAL BINARY
9223372036854775807 1111111111111111111111111111111111111
11111111111111111111111111

#sh dec2binary.sh 9223372036854775808
DECIMAL BINARY
dec2binary.sh:line 13:[:9223372036854775808:integer expression expected
9223372036854775808

NOTE:My bash can handle upto 9223372036854775807.
But with bc command you can do more.

# echo 'obase=2;9223372036854775808'|bc
1000000000000000000000000000000000000000000000000000000000000000

1 comment: