Is std :: bitet bit-order portable?

Does C ++ talk about bit ordering? I especially work on protocol packet mockups, and I doubt if there is a portable way to indicate that a certain number should be written in bits 5,6,7, where bit 5 is the “most significant”.

My questions:

  • - 0x01, always represented as a byte with bit 7 set?
  • bitset<8>().set(7).to_ulong() always 1?
+8
c ++ portability bitset
source share
3 answers

From 20.5 / 3 (ISO / IEC 14882: 2011)

When converting an object of a bit bit of a class and a value of some integer type, the position of the bit position corresponds to the value of bits 1 <pos.

That is, bitset<8>().set(7).to_ulong() guaranteed (1 << 7) == 128 .

+11
source share

the bitset does not serialize, so you don't need to (need) to know. Use serialization / deserialization.

- bitset <8> (). set (7) .to_ulong () is always 1

No, not on my car (see below).

However, I would certainly expect iostream operators to behave portablely:

 #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; } 

Print

 128 10000000 128 10000000 
+2
source share

If the question is whether you can gladly ignore platform content when sending binary objects over the network, you cannot answer. If the question arises whether the same code compiled on two different platforms will give the same results, then the answer is yes.

+2
source share

All Articles