Binary Serialization of std::bitset

后端 未结 6 1646
醉酒成梦
醉酒成梦 2020-12-17 16:52

std::bitset has a to_string() method for serializing as a char-based string of 1s and 0s. Obviously, this us

6条回答
  •  孤城傲影
    2020-12-17 17:18

    this might help you, it's a little example of various serialization types. I added bitset and raw bit values, that can be used like the below.

    (all examples at https://github.com/goblinhack/simple-c-plus-plus-serializer)

    class BitsetClass {
    public:
        std::bitset<1> a;
        std::bitset<2> b;
        std::bitset<3> c;
    
        unsigned int d:1; // need c++20 for default initializers for bitfields
        unsigned int e:2;
        unsigned int f:3;
        BitsetClass(void) { d = 0; e = 0; f = 0; }
    
        friend std::ostream& operator<<(std::ostream &out,
                                        Bits const m
        {
            out << bits(my.t.a);
            out << bits(my.t.b);
            out << bits(my.t.c);
    
            std::bitset<6> s(my.t.d | my.t.e << 1 | my.t.f << 3);
            out << bits(s);
    
            return (out);
        }
    
        friend std::istream& operator>>(std::istream &in,
                                        Bits my)
        {
            std::bitset<1> a;
            in >> bits(a);
            my.t.a = a;
    
            in >> bits(my.t.b);
            in >> bits(my.t.c);
            std::bitset<6> s;
            in >> bits(s);
    
            unsigned long raw_bits = static_cast(s.to_ulong());
            my.t.d = raw_bits & 0b000001;
            my.t.e = (raw_bits & 0b000110) >> 1;
            my.t.f = (raw_bits & 0b111000) >> 3;
    
            return (in);
        }
    };
    

提交回复
热议问题