Thursday, May 31, 2007

Convert Decimal to Hexadecimal, Octal or Binary using typeset

Here is a quick and dirty way of converting a decimal number to hexadecimal, octal, or binary. Below is an inline script followed by a normal shell script file. There are some non-looping examples toward the end of the post.

# ksh
# for i in 100 102 103 104 105 110 1000
> do
>
> typeset -i16 hex
> hex=$i
> print $i equals $hex in hexadecimal
>
> typeset -i8 oct
> oct=$i
> print $i equals $oct in octal
>
> typeset -i2 bin
> bin=$i
> print $i equals $bin in binary
>
>print
> done

100 equals 16#64 in hexadecimal
100 equals 8#144 in octal
100 equals 2#1100100 in binary

102 equals 16#66 in hexadecimal
102 equals 8#146 in octal
102 equals 2#1100110 in binary

103 equals 16#67 in hexadecimal
103 equals 8#147 in octal
103 equals 2#1100111 in binary

104 equals 16#68 in hexadecimal
104 equals 8#150 in octal
104 equals 2#1101000 in binary

105 equals 16#69 in hexadecimal
105 equals 8#151 in octal
105 equals 2#1101001 in binary

110 equals 16#6e in hexadecimal
110 equals 8#156 in octal
110 equals 2#1101110 in binary

1000 equals 16#3e8 in hexadecimal
1000 equals 8#1750 in octal
1000 equals 2#1111101000 in binary

Or put it in a script and specify an argument list via CLI

# vi my_converter.ksh

#!/bin/ksh

if [ $# = 0 ]; then
echo Add an argument list
exit
fi

for i in $*
do

typeset -i16 hex
hex=$i
print $i equals $hex in hexadecimal

typeset -i8 oct
oct=$i
print $i equals $oct in octal

typeset -i2 bin
bin=$i
print $i equals $bin in binary
print
done

:wq!

# chmod 755 my_converter.ksh

# my_converter.ksh 23 32 33 (Michael Jordan, Magic Johnson, Larry Bird)

No looping examples

# sh
Convert Decimal to Hexadecimal
# echo 'obase=16;100'| bc
64

Convert Decimal to Decimal
# echo 'obase=10;10'| bc
10

Convert Decimal to Octal
# echo 'obase=8;34'| bc
42

Convert Decimal to Binary
# echo 'obase=2;10'| bc
1010

Binary, Octal, Hexadecimal to Decimal
# ksh
# echo $((2#101010))
42
# echo $((8#52))
42
# echo $((16#2A))
42


3 comments:

Anonymous said...

You could use normal ksh93 math constructs instead of "typeset", for example via:
$ print -- $(( 2#0101 + 4#0303 ))
56

David said...

for some of you looking for an online converter, check this good hex to decimal converter
Pretty good!
Enjoy!
David

Hanky Panky said...

Great,

you can also tell bc the input number base:

echo 'ibase=2;obase=16;1100' | bc

echoes 'c'