Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8050291
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T07:02:20+00:00 2026-06-05T07:02:20+00:00

I need to read and write numerical values of specified bit-length (not necessarily multiples

  • 0

I need to read and write numerical values of specified bit-length (not necessarily multiples of 8) at a specified bit-offset in a memory buffer, the most-significant bit first.

For example, writing the value of 5 at offset 6 and bit-length 4:

before: 11111111 11111111
bits:         ^^ ^^
after:  11111101 01111111

So the functions I’m looking for may be defined like this:

unsigned get_bits (unsigned char *buffer, int offset, int bit_size);
void set_bits (unsigned char *buffer, int offset, int bit_size, 
                             unsigned value);

And example usage:

set_bits (buffer, 6, 4, 5);
unsigned v = get_bits (buffer, 6, 4);
assert (v == 5);

The functions will be used to read/write a small number of values in a relatively big buffer (filtering network traffic of high volume), so I discarded (perhaps wrongly) using std::bitset.

Are there any existing libraries which could be used to achieve/simplify this task? Any suggestions regarding implementing it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T07:02:26+00:00Added an answer on June 5, 2026 at 7:02 am

    Bit-fiddling is seldom easy. Here’s a complete working example of how to do what you want.

    The big problem here is reading and writing blocks of numbers across byte boundaries. Problems are always easier if you break them into bite-size chunks, if you’ll pardon the pun.

    Firstly I created a class like std::bitset that can wrap a user-defined buffer. It lets us fiddle with individual bits in a big buffer of binary data.

    #include <cassert>  // for assert
    #include <cstring>  // for memset
    
    // A wrapper for a data buffer providing bit-level access.
    class BitBuffer {
    public:
        BitBuffer (unsigned char *src_buffer, size_t byte_size)
            : m_data( src_buffer ), m_size( byte_size )
        {
            if (m_size) assert(m_data);
        }
    
        // Clear the buffer (set all bits to 0).
        void clear () {
            memset( m_data, 0, m_size );
        }
    
        // Get an individual bit's value.
        bool get (size_t bitpos) const {
            assert( bitpos / 8 < m_size );
            return m_data[ bitpos / 8 ] & ( 1 << ( bitpos % 8 ) );
        }
    
        // Set an individual bit's value.
        void set (size_t bitpos, bool val=true) {
            assert( bitpos / 8 < m_size );
            if( val ) {
                m_data[ bitpos / 8 ] |= ( 1 << ( bitpos % 8 ) );
            } else {
                m_data[ bitpos / 8 ] &= ~( 1 << ( bitpos % 8 ) );
            }
        }
    
        // Switch off a bit.
        void reset (size_t bitpos) { 
            set( bitpos, false );
        }
    
        // Flip a bit.
        void flip (size_t bitpos) {
            set( bitpos, ! get( bitpos ) );
        }
    
        // Return the size of the buffer in bytes.
        size_t byte_size () const { return m_size; }
    
        // Return the size of the buffer in bits.
        size_t bit_size () const { return m_size * 8; }
    
        // Return a const pointer to the buffer.
        unsigned char const *  buffer () const { return m_data; }
    
    private:
        unsigned char * m_data;
        size_t m_size;
    };
    

    Then I wrote some functions to get and set blocks of bits from the buffer, MSB first.

    unsigned get_bits (BitBuffer& buffer, size_t offset, size_t bit_size)
    {
        unsigned bits = 0;
        for (size_t i = 0; i < bit_size; i++) {
            // We reverse the order of the bits, so the first bit read
            // from the buffer maps to the high bit in 'bits'.
            bits |= ( buffer.get( offset + i ) << (bit_size - 1 - i) );
        }
        return bits;
    }
    
    void set_bits (BitBuffer& buffer, size_t offset, size_t bit_size, unsigned bits)
    {
        for (size_t i = 0; i < bit_size; i++) {
            // We reverse the order of the bits, so the high bit of 'bits'
            // gets written to the buffer first.
            bool bit_value = bits & ( 1 << (bit_size - 1 - i) );
            buffer.set( offset + i, bit_value );
        }
    }
    

    And a test harness:

    #include <cstdio>
    
    // Print the bits of the buffer to stdout.
    void dump_buffer (BitBuffer& buffer)
    {
        for (size_t i = 0; i < buffer.bit_size(); i++) {
            printf( "%i", buffer.get(i) );
        }
        printf("\n");
    }
    
    int main()
    {
        const size_t byte_size = 4;  // size of buffer in bytes
        unsigned char * raw_buffer = new unsigned char[ byte_size ];
    
        BitBuffer buffer( raw_buffer, byte_size );
        buffer.clear();
    
        printf("Test #0: contents of 4-byte buffer:\n");
    
        // Show the buffer.
        dump_buffer( buffer );
    
        printf("\nTest #1: setting and flipping bits:\n");
    
        // Set some bits
        buffer.set( 5 );
        buffer.set( 10 );
        buffer.set( 12 );
        buffer.set( 31 );
    
        // Show the buffer.
        dump_buffer( buffer );
    
        // Read some bits.
        printf( "Value at 12 before flip: %i\n", buffer.get( 12 ) );
        buffer.flip( 12 );
        printf( "Value at 12 after flip: %i\n", buffer.get( 12 ) );
    
        printf("\nTest #2: setting all 1's, and writing 5, length 4 to offset 6:\n");
    
        // Fill with 1's.
        set_bits(buffer, 0, 32, 0xFFFFFFFF);
    
        // Set 5 at offset 6, bit size 4.
        set_bits(buffer, 6, 4, 5);
        assert( get_bits(buffer, 6, 4) == 5 );
    
        // Show the buffer.
        dump_buffer( buffer );
    
        // All done.
        delete raw_buffer;
        return 0;
    }
    

    To compile, just dump all this in one file and compile. Output of test run:

    Test #0: contents of 4-byte buffer:
    00000000000000000000000000000000
    
    Test #1: setting and flipping bits:
    00000100001010000000000000000001
    Value at 12 before flip: 1
    Value at 12 after flip: 0
    
    Test #2: setting all 1's, and writing 5, length 4 to offset 6:
    11111101011111111111111111111111
    

    Let me know if you find it useful, or if you have any problems with it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need raw read data from and write data into drive..not via existed filesystem
I need to read/write a string of characters using the IBM-1047 character encoding. But
I need to read/write to the user's address book and am using the AddressBookUI
I'm trying to upload a file via URLConnection, but I need to read/write it
I need to read and write(update) some remote machine file.I am able to find
I need to read and write some data through named pipes. I have tested
I need to read and write signed and unsigned integers with a SeekableByteChannel in
In my task i need to read and write the file in Raw folder.
In my project, there is a need to read and write to binary file,
I need to read from and write to Excel spreadsheets using Delphi 2010. Nothing

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.