showbits( ) Function in C with Examples
Bitwise operators are operators (just like +, *, &&, etc.) that operate on ints and uints at the binary level. This means they look directly at the binary digits or bits of an integer. This all sounds scary, but in truth, bitwise operators are quite easy to use and also quite useful! It is important, though, that you have an understanding of binary numbers and hexadecimal numbers.
Let’s take a look at the different bitwise operators:
- & (bitwise AND)
- | (bitwise OR)
- ~ (bitwise NOT)
- ^ (bitwise XOR)
- << (bitwise left shift)
- >> (bitwise right shift)
- >>> (bitwise unsigned right shift)
- &= (bitwise AND assignment)
- |= (bitwise OR assignment)
- ^= (bitwise XOR assignment)
- <<= (bitwise left shift and assignment)
- >>= (bitwise right shift and assignment)
- >>>= (bitwise unsigned right shift and assignment)
In this article, the focus is on the showbits() function. Let’s see how it is related to Bitwise Operators.
showbits( ) Function
This function mainly deals with bitwise operators concepts. Let’s have a look at the below C program to understand showbits() function.
- All that is being done in this function is using an AND operator and a variable andmask. andmask variable is used to check the status of individual bits. If the bit is OFF we print a 0 otherwise we print a 1.
- The first time through the loop, the variable andmask will contain the value 1000000000000000, which is obtained by left-shifting 1, fifteen places.
- If the variable n’s most significant bit is 0, then k would contain a value 0, otherwise, it would contain a non-zero value.
- If k contains 0 then printf( ) will print out 0 otherwise it will print out 1.
- On the second go-around of the loop, the value of i is decremented, and hence the value of andmask changes, which will now be 100000000000000. This checks whether the next most significant bit is 1 or 0, and prints it out accordingly. The same operation is repeated for all bits in the number.
If the binary of decimal numbers is required, then basically all integers are actually in binary in computer. Its just that it is turned into a string that is the decimal representation of that value when it is printed using printf and “%d”. If result in some other base (e.g. base 2 or binary) is required, provide the proper printf format string if it exists (e.g. “%x” for hex) or just build that string and print it out.
Below is the code that can build the string representation of an integer in any base in [2,36].
Explanation: The function base_change() displays the binary representation of any integer or character value. For now, it is sufficient to know that base_change() function displays the binary equivalent of the integer number.