Bitwise ops on char[array] in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vusak
    New Member
    • Apr 2007
    • 7

    #1

    Bitwise ops on char[array] in c++

    can anyone tell me if there is a way to apply bitwise operations, like & ^ | ~ << >> to an array of unsigned char as one contiguous block of bits?

    ie. say i have

    unsigned char value[5]
    unsigned char mask[5]

    is doing something like (value[] &= mask[]) reliable or well defined?

    currently im implementing it as

    for( i = 0 to 5 ) { value[i] &= mask[i] }

    which isnt a problem, however if thats a loop i dont need, then it would be nice to drop it

    moreso my functions for << and >> are pretty ugly and i know im losing the benefits of bitwise stuff with the way ive done it

    thanks
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    If you are really using C++, then you should be using the bitset<> template from the C++ Standard LIbrary:

    [code=cpp]
    bitset<32> mybits; //creates 32 bits
    mybits.Set(15); //set bit 15 to true
    mybits.Reset(8) ; //reset bit 8 to false
    mybits.flip(5); //flip true to false or false to true as the case may be
    mybits.test(20) //returns true if bit 20 is true and false otherwise.
    etc...
    [/code]

    The use of C-style bitfields is not compatible with C++.

    Comment

    • vusak
      New Member
      • Apr 2007
      • 7

      #3
      ive wrapped it all up nicely in class, i didnt find bitset flexible enough for my needs, im trying to maintain hardware and compiler independence, although im not too experienced with working on this kind of data type in this way

      but if there is a way to perform bitwise ops across contiguous bits of memory, id love to know, ive been searching all over

      Comment

      Working...