Translate

Archives

Converting Integer to Different Base in KSH93

The classical way to convert an integer to different base, e.g. decimal (base 10) to binary (base 2), in a shell script is to use the `bc` utility as shown in the following example:

$ num=20; echo "obase=2;$num" | bc
10100
$ 


You do not, however, have to use this method if you are using ksh93. You can do the conversion using printf or print -f as shown in the following examples:

$ num=20; printf "%..2d\n" $num   
10100
$ num=20; printf -f "%..2d\n" $num   
10100
$ num=20; printf "%..8d\n" $num
24
$ num=20; printf "%..16d\n" $num
14
num=20; printf "%16.2.16d\n" $num
              14
$ num=20; printf "%#.2.16d\n" $num  
16#14
$ num=20; printf "%#8.2.16d\n" $num
   16#14
$ num=20; print -f "%#8.2.16d\n" $num 
   16#14
$ 


This functionality is tersely documented in the output of printf –man

– Each of the integral format specifiers can have a third modifier after width and precision that specifies the base of the conversion from 2 to 64. In this case the # modifier will cause base# to be prepended to the value.

The zsh shell is the only other shell that I am aware of which has similar builtin functionality albeit with a different syntax.

Enjoy!

Comments are closed.