Pages

Tuesday, June 7, 2011

Base conversion in BASH

As programmers, we often encounter numbers written in binary or hexadecimal format. Mostly it is written as the context is made easier. For example, a set of flags is better represented as binary than integer. Here's an example :-
#define IS_TRUE        0b01     // same as 1
#define IS_FALSE       0b00     // same as 0
#define CONFIRM        0b10     // same as 2
#define DOUBTFUL       0b00     // same as 0
This example might not be very common, but this demonstrates the use of binary representation. These flags are useful at binary level to facilitate " bit-level AND " and various other operations.

In such scenarios, it could get confusing as to what the number represents in integers. Many, here, would suggest creating a program in the language of your choice and using it for base conversion. So, here I explain how one can use BASH itself.

BASH allows base conversion very easily. Fire up a terminal and try this :-
echo $((2#1010101))
I assume, I needn't explain $((<operation>)) is necessary for mathematical operations in BASH.  The output of the above command is 85, which is the decimal value of the number  "0b1010101".

So here we have a simple base converter. Interestingly, the base conversion allows to convert from any base to decimal this easily  :

<base>#<number_in_base>

The above is sufficient to convert number given in any base to decimal value. Go ahead, try it out.

No comments:

Post a Comment