Fill A Range of Bits with 1's

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const unsigned int WORD_BITSIZE = 32;
typedef unsigned int uint;

static uint ones[] = { 0x0,

                0x1,        0x3,        0x7,        0xf,
               0x1f,       0x3f,       0x7f,       0xff,
              0x1ff,      0x3ff,      0x7ff,      0xfff,
             0x1fff,     0x3fff,     0x7fff,     0xffff,
            0x1ffff,    0x3ffff,    0x7ffff,    0xfffff,
           0x1fffff,   0x3fffff,   0x7fffff,   0xffffff,
          0x1ffffff,  0x3ffffff,  0x7ffffff,  0xfffffff,
         0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff };



/*
 * one_fill_bits
 *

   Starting with bit low_bit to bit high_bit, set all bits to 1.
   Bits are numbered from zero.

 */
static void one_fill_bits( uint *dest, uint low_bit, uint high_bit )
{

  if (low_bit < high_bit) {
    uint word_num;
    int bit_start, i, word_cnt;
    uint mask_bits, mask, end_bits;

    word_num = low_bit/WORD_BITSIZE;
    word_cnt = word_num + 1;
    bit_start = low_bit % WORD_BITSIZE;
    if (word_cnt * WORD_BITSIZE > high_bit) {
      mask_bits = (high_bit - low_bit) + 1;
    }
    else {
      mask_bits = WORD_BITSIZE - bit_start;
    }
    mask = ones[ mask_bits ];
    mask = mask << bit_start;
    dest[word_num] = dest[word_num] | mask;

    word_num++;
    word_cnt++;

    while (word_cnt * WORD_BITSIZE <= (high_bit+1)) {
      dest[word_num] = 0xffffffff;
      word_num++;
      word_cnt++;
    }

    end_bits = (high_bit+1) % WORD_BITSIZE;
    if (word_num * WORD_BITSIZE < (high_bit+1) && end_bits != 0) {
      dest[word_num] = dest[word_num] | ones[ end_bits ];
    }
  }
} /* one_fill_bits */


back to Miscellaneous Software