How to Insert 1 Bit Into An Integer in C/C++

Inserting a bit into an integer, means to insert a bit into a specific position of an integer, with the highest bit removed. For example, for a one byte integer 11001010, if I insert a 1 at digit position 4, which is marked here 1100|1010 as |, the most significant bit, which is the left most 1, would be eliminated and the rest of the 3 bits on the left side of | would be shifted to the left for 1 bit.

This is not hard to implement, but surprisingly I cannot find any existing code snippet for such a simple job.

Here is the code snippet I wrote for C++ (which should also work for C with slight modification), and it can be easily translated into most other languages. Here, T is any integer type.

#include <stddef.h> // for size_t
template <typename T> // if used in C, remove this line and replace T with an integer type
T insert_bit(T n,   // The integer we are going to insert into
             size_t position, // position is the position of the new bit to be inserted
             bool new_bit) // whether the newly inserted bit is true or false
{
    T x = n;
    T y = x;
    x <<= 1;
    if (new_bit)
        x |= (((T) 1) << position);
    else
        x &= ~(((T) 1) << position);
    x &= ((~((T) 0)) << position);
    y &= ~((~((T) 0)) << position);
    x |= y;
    return x;
}

Don’t hesitate to comment if you think there is a better (more elegant or faster) way.

Leave a Reply

Your email address will not be published.