Sunday, December 15, 2024

Some bit manipulations

 This C++ code has bits access routines to get and set some bits:


dataBits.h:




#include <cstdint>
#include <iostream>

template <typename T>
class DataBits
{
public:
DataBits(T v=0) : m_data(v) {};
        
        T get() const { return m_data; }

        void set(T v) { m_data = v; }

        // 0-based
        template <typename TB>
static constexpr TB BitMask(int startpos, int endpos)
{
return TB((1<<(endpos-startpos+1))-1) << startpos;
        }

        constexpr T GetBits(int startpos, int endpos)
        {
            return (m_data & BitMask<T>(startpos, endpos)) >> startpos;
        }

        void SetBits(int startpos, int endpos, T newData)
        {
            auto mask = BitMask<T>(startpos, endpos);
            m_data = (m_data & ~mask) | ((newData << startpos) & mask);
        }

private:
    T  m_data;

};



main.cpp:

#include <iostream>
#include <format>
#include <bitset>
#include <iomanip>
#include "dataBits.h"


int main()
{
    std::cout << std::format("{:#04x}", 0x0e) << std::endl;
    std::cout << "BitMask[1..3] = " << std::hex << "0x" << DataBits<uint32_t>::BitMask<uint32_t>(1,3) << std::endl;

    DataBits bits = 0b1110101001010011;
    std::cout << "bits = " << std::setw(55) << std::bitset<32>(bits.get()) << std::endl;
    auto newbits = 0b010;
    bits.SetBits(13, 15, newbits);
    std::cout << "bits with bits[13..15]=" << std::bitset<3>(newbits) << " -> " << std::bitset<32>(bits.get()) << std::endl;
    std::cout << "BitMask[1..3] = " << std::hex << "0x" << DataBits<uint32_t>::BitMask<uint32_t>(1,3) << std::endl;
    std::cout << "data @bits[13..15] = " << std::bitset<3>(bits.GetBits(13,15)) << std::endl;
    return 0;
}