Is there a portable alternative to C++ bitfields

前端 未结 5 1332
梦谈多话
梦谈多话 2021-02-05 06:53

There are many situations (especially in low-level programming), where the binary layout of the data is important. For example: hardware/driver manipulation, network protocols,

5条回答
  •  不要未来只要你来
    2021-02-05 07:25

    It's simple to implement bit fields with known positions with C++:

    template
    struct BitField {
        T *data;
    
        BitField(T *data) : data(data) {}
    
        operator int() const {
            return ((*data) >> POS) & ((1ULL << SIZE)-1);
        }
    
        BitField& operator=(int x) {
            T mask( ((1ULL << SIZE)-1) << POS );
            *data = (*data & ~mask) | ((x << POS) & mask);
            return *this;
        }
    };
    

    The above toy implementation allows for example to define a 12-bit field in a unsigned long long variable with

    unsigned long long var;
    
    BitField muxno(&var);
    

    and the generated code to access the field value is just

    0000000000000020 <_Z6getMuxv>:
      20:   48 8b 05 00 00 00 00    mov    0x0(%rip),%rax  ; Get &var
      27:   48 8b 00                mov    (%rax),%rax     ; Get content
      2a:   48 c1 e8 07             shr    $0x7,%rax       ; >> 7
      2e:   25 ff 0f 00 00          and    $0xfff,%eax     ; keep 12 bits
      33:   c3                      retq   
    

    Basically what you'd have to write by hand

提交回复
热议问题