Base Conversion

Some one in a chat room asked about converting from hex to decimal. The usual answers came up, use mdb or adb or dtcalc oddly the vastly superior gnome-calculator did not get a mention. Anyway my solution was declared “cool” by one person so that is enough to get on the blog.

The solution is the korn shell. Converting from hex to decimal do this:

echo $(( 16#4000 ))

Will convert 4000 to decimal

Converting to hex is slightly harder:

typeset -i16 x
x=4000
echo $x

Which cries out for a shell function:


function convert_base
{
        typeset -i${2:-16} x
        x=$1
        echo $x
}

Putting that in a file called convert_base in your FPATH thus allowing:


: enoexec.eu FSS 12 $; convert_base 4000
16#fa0
: enoexec.eu FSS 13 $; convert_base 4000 2
2#111110100000
: enoexec.eu FSS 14 $; convert_base 16#4000 2
2#100000000000000
: enoexec.eu FSS 15 $; convert_base 16#4000 10
16384
: enoexec.eu FSS 16 $;

Well I like it.

Tag: , ksh




        
    
Comments:

You can also use the "ibase" and "obase" capabilities of bc: $ bc ibase=10 obase=16 123434 1E22A You can even convert decimal to binary: $ bc ibase=10 obase=2 16 10000

Posted by Matty on May 05, 2005 at 03:10 PM BST #

Did not know about that one

However it is a bit disappointing that it can't cope with larger bases which thankfully the korn shell can

: principia IA 5 $; bc
ibase=10
obase=2
16
10000
ibase=17
input base is too large
: principia IA 6 $; echo $(( 17#16 ))
23
: principia IA 7 $; echo $(( 17#10 ))
17

Posted by Chris Gerhard on May 05, 2005 at 04:48 PM BST #

I don't know

Posted by guest on May 09, 2005 at 10:14 AM BST #

# try in ksh this !!: print $((0x100)) # and on any unix shell printf "%x\\n" 256

Posted by Francois on February 07, 2006 at 08:20 AM GMT #

Oops.. 0x100 works only on Solaris ksh. $((16#100)) works on Aix Solarix and RedHat...

Posted by francois on February 07, 2006 at 09:54 AM GMT #

I always seem to default to perl:

perl -e 'print sprintf( "%.4d", 0xCAFE ), "\\n";'

or something along those lines

Posted by ed neville on December 23, 2008 at 02:01 PM GMT #

Post a Comment:
Comments are closed for this entry.
About

This is the old blog of Chris Gerhard. It has mostly moved to http://chrisgerhard.wordpress.com

Search

Archives
« April 2014
MonTueWedThuFriSatSun
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today