0

I am porting some code written in Java to C11. The Java code uses BitSet to flip in flip bits in a vector. I know there is corresponding BitSet for c++, but I am not sure if there something similar available for c11. I have to use c11 per requirements. I am not too familiar with the newer set of functions in c11, as most of my previous code have either been in ANSI-C or C99.

Is something like this available in C (C11) or do I need to write my own function that maps to a memory group and then uses bit operators?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Andy
  • 2,469
  • 1
  • 25
  • 25
  • 3
    I'm going to remove the Java tag, since this question doesn't really have to do with Java (other than using a Java class as a shorthand to describe your desired behavior). But please note that questions asking for tools or libraries [are off topic for Stack Overflow](http://stackoverflow.com/help/on-topic), so this question may be closed anyway. – yshavit Dec 31 '15 at 17:40
  • What's wrong with simple `OR`ing/`AND`ing?? – Eugene Sh. Dec 31 '15 at 17:58
  • The duplicate question more or less answers the question, so thank you for pointing that out. The basic question is different though, as I am asking if C11 has support for BitSit or not, not how to implement. I am not asking specifically how to implement it, nor do I ask for libraries; it's a C11 language question. Is that off topic? – Andy Jan 01 '16 at 11:26

2 Answers2

2

There is no BitSet, per se, in C (C11 or otherwise). C has direct access to memory, so you can just use data types directly. For example, a bit set with 8 bits can be made with a uint8_t as follows.

Usage

uint8_t bitset = 0;
bitset = bitset | (1 << 4); // set 4th bit, like BitSet.set(4)
bitset = bitset & ~(1 << 3); // unset 3rd bit, like BitSet.clear(3)
bitset = ~bitset; // flip the bits, like BitSet.flip(0, 7)
bitset = bitset ^ (1 << 4); // flip the 4'th bit like BitSet.flip(4)

Read more about bitwise operators at https://en.wikipedia.org/wiki/Bitwise_operations_in_C

AlexPogue
  • 757
  • 7
  • 14
  • If you want to make it more comprehensive, flipping individual bits would be done by `xor` ing with `1`...BTW, unsetting bits won't work this way... It should be `bitset & ~(1 << 3)`. Anyway, edited it for you.. – Eugene Sh. Dec 31 '15 at 18:05
  • Thanks! I was trying to remember how to flip individual bits. And good catch.. Bitshifting 0 doesn't make any sense. – AlexPogue Dec 31 '15 at 18:10
  • Thank you for the answer! As the vectors are at least a thousand bits long, I will instead use the method described in the linked answer. Sorry for missing that when searching for an answer. – Andy Jan 01 '16 at 11:29
0

As far as I'm concerned, no such functions exist in the C standard library. You have to write that yourself. Luckily, a bitset is one of the easiest data-structures to implement.

fuz
  • 88,405
  • 25
  • 200
  • 352