bitops: merged bitset functions and cleaned up code

tags/0.1.0
S.J.R. van Schaik 8 years ago
parent 5a8bf83c7b
commit 57f72ea5f5
  1. 7
      include/bitops.h
  2. 10
      include/bitset.h
  3. 54
      source/bitops.c
  4. 61
      source/bitset.c

@ -1,3 +1,10 @@
#pragma once
#include <stdlib.h>
unsigned ilog2(unsigned n);
int is_bit_set(void *base, size_t n);
void set_bit(void *base, size_t n);
void clear_bit(void *base, size_t n);
size_t next_set_bit(void *base, size_t n);
size_t next_clear_bit(void *base, size_t n);

@ -1,10 +0,0 @@
#pragma once
#include <stdint.h>
#include <stdlib.h>
int is_bit_set(void *set, size_t n);
void set_bit(void *set, size_t n);
void clear_bit(void *set, size_t n);
size_t next_set_bit(void *set, size_t len);
size_t next_clear_bit(void *set, size_t len);

@ -1,4 +1,10 @@
#include <stdint.h>
#include <bitops.h>
#include <macros.h>
#define BIT_WORD(n) ((n) / BIT_SIZE(unsigned long))
#define BIT_MASK(n) (1UL << ((n) % BIT_SIZE(unsigned long)))
unsigned ilog2(unsigned n)
{
@ -9,3 +15,51 @@ unsigned ilog2(unsigned n)
return ret;
}
int is_bit_set(void *base, size_t n)
{
unsigned long *word = (unsigned long *)base + BIT_WORD(n);
unsigned long mask = BIT_MASK(n);
return (*word & mask) ? 1 : 0;
}
void set_bit(void *base, size_t n)
{
unsigned long *word = (unsigned long *)base + BIT_WORD(n);
unsigned long mask = BIT_MASK(n);
*word |= mask;
}
void clear_bit(void *base, size_t n)
{
unsigned long *word = (unsigned long *)base + BIT_WORD(n);
unsigned long mask = BIT_MASK(n);
*word &= ~mask;
}
size_t next_set_bit(void *base, size_t n)
{
size_t i;
for (i = 0; i < n; ++i) {
if (is_bit_set(base, i))
return i;
}
return SIZE_MAX;
}
size_t next_clear_bit(void *base, size_t n)
{
size_t i;
for (i = 0; i < n; ++i) {
if (!is_bit_set(base, i))
return i;
}
return SIZE_MAX;
}

@ -1,61 +0,0 @@
#include <bitset.h>
#include <macros.h>
int is_bit_set(void *set_, size_t n)
{
uint8_t *set = set_;
uint8_t *word, mask;
word = set + n / BIT_SIZE(*set);
mask = (1 << (n % BIT_SIZE(*set)));
return (*word & mask) ? 1 : 0;
}
void set_bit(void *set_, size_t n)
{
uint8_t *set = set_;
uint8_t *word, mask;
word = set + n / BIT_SIZE(*set);
mask = (1 << (n % BIT_SIZE(*set)));
*word |= mask;
}
void clear_bit(void *set_, size_t n)
{
uint8_t *set = set_;
uint8_t *word, mask;
word = set + n / BIT_SIZE(*set);
mask = (1 << (n % BIT_SIZE(*set)));
*word &= ~mask;
}
size_t next_set_bit(void *set_, size_t len)
{
uint8_t *set = set_;
size_t n;
for (n = 0; n < len; ++n) {
if (is_bit_set(set, n))
return n;
}
return SIZE_MAX;
}
size_t next_clear_bit(void *set_, size_t len)
{
uint8_t *set = set_;
size_t n;
for (n = 0; n < len; ++n) {
if (!is_bit_set(set, n))
return n;
}
return SIZE_MAX;
}
Loading…
Cancel
Save