Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::bitset bit-order portable?

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:

  • is 0x01 always represented as a byte with bit 7 set?
  • is bitset<8>().set(7).to_ulong() always equal to 1?
like image 256
xtofl Avatar asked Oct 25 '11 13:10

xtofl


People also ask

Is Bitset faster than vector bool?

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.

How much memory does Bitset use?

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.

What data type is a Bitset?

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.

How do I convert Bitset to all bits to 1?

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.


2 Answers

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.

like image 168
hamstergene Avatar answered Sep 19 '22 19:09

hamstergene


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
like image 32
sehe Avatar answered Sep 16 '22 19:09

sehe