CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: bit operations

  1. #1
    Join Date
    Jun 2005
    Posts
    3

    bit operations

    Hi,

    I was hoping I could get some insight on the best way to remove a bit from an array of bytes.

    For example:

    I have an unsigned char data[10];

    I want to remove bit 5 from the second byte of the array and then shift the remaining bits to the left (the end of the array can be zero padded).

    Does anyone know of an efficient way to accomplish this?

    Thanks!

  2. #2
    Join Date
    Jul 2005
    Posts
    103

    Re: bit operations

    You want to start by checking if std::bitset in <bitset> suits your requirements.

  3. #3
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: bit operations

    ...or else std::vector<bool>.

    You can also implement it yourself and use the bit-shift operators >> and <<. For just one byte it would be something like this:
    Code:
    // erase bit with index 'bit' (0 is least significant), shift bits > 'bit' one bit back
    erase_bit(unsigned char& c, const int bit)
    {
    	c = (c & (0x7F >> (7 - bit))) | ((c & (0xFE << bit)) >> 1);
    }
    By the way, when working with bit-arrays, it is easier to use unsigned values. Also, using 32 bit values is faster, since it reduces the number of elements in your array, compared to 8 bit values.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured