8

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?
xtofl
  • 40,723
  • 12
  • 105
  • 192

3 Answers3

11

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.

hamstergene
  • 24,039
  • 5
  • 57
  • 72
2

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
sehe
  • 374,641
  • 47
  • 450
  • 633
2

If the question is whether you can happily ignore endianness of the platform while sending binary objects over the network, the answer is you cannot. If the question is whether the same code compiled in two different platforms will yield the same results, then the answer is yes.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • My concern is the former - send `bitset.set(7).to_ulong()` to another platform, and have `bitset(received).isset(7)` be `true`. – xtofl Oct 25 '11 at 13:57
  • @xtofl, How are you sending the `std::bitset`? – deft_code Oct 25 '11 at 14:02
  • 1
    @xtofl That will depend on how you serialize the data. If you convert to ASCII, that will be true, if you convert to `long` and then send it over a binary protocol, you will have to use the common `htonl/ntohl` conversions, if you are only modifying a single byte, then you can just send that byte and there is no endianness effect there... – David Rodríguez - dribeas Oct 25 '11 at 14:04