Example C code to set 5 bits starting from position 10

Graphic showing numbers

This is a common embedded software interview bitwise operation question. The magic numbers ‘5’ and ‘10’ are used arbitrarily to make the understanding of the problem easier. The idea of this program is to set 5 bits of a word starting from the bit position 10. Code walk-through and algorithm is explained below.

Code walk-through

This simple C program demonstrates the use of bitwise operators to set 5 bits starting from position 10. This example also implements a helper function print_32bit_binary() to print values in binary representation.

The given number is printed in its binary form by calling the function print_32bit_binary() from main().

The function print_32bit_binary() prints the int number in its binary form by looping through the int bit-width and outputs a character 1 or 0 after testing the corresponding bit position,

Coming to the actual problem of setting the 5 bits starting from position 10 is by creating a bitmask at line,

and ORing the bitmask with the given number at line,

Analyzing the bitmask temp

From the statement, temp = ~(~0 << 5) << (10 + 1 - 5); the code section ~(~0 << 5) creates a value which has only the last 5 bits set to 1. Then the code section (10 + 1 - 5) will point to the 10th bit position (1 is added since the bit position starts from 0 for bitwise operation and 5 is subtracted since 5 bits needs to be set.

Leave a Reply 0

Your email address will not be published. Required fields are marked *