May 30, 2017

Assigning Binary Value to a Variable in C and C++

If you are programming in C and C++ then you may already know that C and C++ do not have native support for binary literal. So you can not simply write the following statement to give a variable a binary value:

int signal = 1110;

However, C and C++'s bitwise operators such as Left Shift operator << and Or operator | can be easily utilised to achieve binary value assignment like shown below:

int signal = 1 << 3 | 1 << 2 | 1 << 1;

The above statement assigns binary value 1110 to the variable signal. The way it works is the very first expression 1 << 3 creates a binary value 1000, and then the expression 1 << 2 creates a binary value 100 and finally the expression 1 << 1 creates a binary value 10. When all these three binary values are combined using the Or operators we get the binary value 1110 like shown below:

Expression            Binary equivalent
1 << 3            =     1000
1 << 2            =     0100
1 << 1            =     0010
                              1110 (after or operations of three expressions)

One advantage about this method of binary assignment is that there is no need for external libraries and such. The example program demonstrating the above method can be downloaded from the following link:

binary_assignment.c

There is also a convenience functions library called imamB which I wrote recently which can be used for getting binary values of variables as a string and vice versa. To use the functions from imamB all you need to do is to include header and source files from imamB package to your project directory. imamB can be download from the following link:

imamB-1.0.zip

Cheers!
Imam