Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q: How bitset are inside?

The question is really simple (to ask), std::bitset<32> is the same thing as uint32_t for the memory? Or it's more like std::array<bool, 32> ?

I usually do something like:

uint32_t  index : 20;
uint32_t  magic : 12;

So it's the same as this code ?

std::bitset<20>  index;
std::bitset<12>  magic;
like image 913
Mathieu Van Nevel Avatar asked Dec 06 '16 13:12

Mathieu Van Nevel


People also ask

How is bitset implemented?

Let's implement bitset in C++, such that following operations can be performed in stated time complexities : init(int size): initializes a bitset of size number of 0 bits. void fix(int pos): Change the bit at position pos to 1.

How big can a bitset be?

Java BitSet size() method The maximum element in the set is the size - 1st element. The default size of the bit set is 64-bit space. If the bit is set at index larger than the current BitSet size, it increases its bit space in the multiplication of 64*n, where n starts from 1, 2, 3, so on.

What is bitset in C?

Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.

What is bitset used for?

C++ Programming A bitset is a dataset that stores multiple boolean values but takes lesser memory space as compared to other data sets that can store a sequence of bits like a boolean array or boolean vector. Bitsets stores the binary bits in a form that takes less memory space, it stores them in compressed from.


1 Answers

uint32_t  index : 20;
uint32_t  magic : 12;

So it's the same as this code ?

std::bitset<20>  index;
std::bitset<12>  magic;

Absolutely not, and it's very important that you understand the difference.

First, the internal representation of std::bitset<> is down the implementation.

With that out of the way we should examine the difference between the two code snippets above.

In c++ a bitfield is not a discrete object. This has important implications in multi-threaded code.

This is because c++11 and greater guarantees that unprotected access from two threads to two discrete objects is safe, but access of the same non-const object by two more more threads is a data race unless protected by a mutex.

In the above bitset code it would be correct to say:

thread1: index = 10;

thread2: auto x = magic;

Because they are discrete objects and therefore guaranteed not to cause data races when accessed from different threads.

In the bitfield code this would not be safe. The update of index would be a race with the reading of magic, and this is undefined behaviour.

like image 105
Richard Hodges Avatar answered Oct 19 '22 19:10

Richard Hodges