Does C++ say anything on bit-ordering? I'm especially working on protocol packet layouts, and I'm doubting whether there is a portable way to specify that a certain number be written into bits 5,6,7, where bit 5 is the 'most significant'.
My questions:
bitset<8>().set(7).to_ulong()
always equal to 1?So it seems under these conditions, bitset is faster than vector when the code is optimized, while vector actually comes out on top by a (very) small margin when it's not.
As expected, the BitSet with the same number of bits consumes around 1 KB, which is far less than the boolean[]. The above code will compute the object size for both types of bit-vectors with different lengths.
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.
bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.
From 20.5/3 (ISO/IEC 14882:2011)
When converting between an object of class bitset and a value of some integral type, bit position pos corresponds to the bit value 1 << pos.
That is, bitset<8>().set(7).to_ulong()
is guaranteed to be (1 << 7) == 128
.
bitset doesn't do serialization, so you don't (need to) know. Use serialization/deserialization.
is bitset<8>().set(7).to_ulong() always equal to 1
No, not on my machine (see below).
However, I'd certainly expect the iostream operators to behave portably:
#include <bitset>
#include <sstream>
#include <iostream>
int main()
{
std::bitset<8> bits;
std::cout << bits.set(7).to_ulong() << std::endl;
std::stringstream ss;
ss << bits;
std::cout << ss.rdbuf() << std::endl;
std::bitset<8> cloned;
ss >> cloned;
std::cout << cloned.set(7).to_ulong() << std::endl;
std::cout << cloned << std::endl;
}
Prints
128
10000000
128
10000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With