How to access the individual bits of a value stored?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bikash Kumar Mishra
    New Member
    • Sep 2010
    • 1

    How to access the individual bits of a value stored?

    how to access the bits of a value stored in memory as such?
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    you may like to see bitwise operators in C/C++

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      Either that, or you can use a union to map a bitmaped structure on top of your input value, like so:

      Code:
      union myConverter
      {
        long  baseValue
        struct
        {
          unsigned  bit0 : 1;
          unsigned  bit1 : 1;
          unsigned  bits2to31 : 30;
        };
      } convert;
      
      convert.baseValue = 12345;
      convert.bit0 = 0;                // baseValue now = 12344

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        But a bit field structure like that is very platform dependent. If you moved your code to another platform or compiler even you have no guarantee that the result would be baseValue = 12344 because the order that bit fields are placed in the base field is platform defined.

        Comment

        • Oralloy
          Recognized Expert Contributor
          • Jun 2010
          • 988

          #5
          Banfa,

          You're right. They are platform dependent. Just like that long is guaranteed to be a minimum of 32 bits.

          It's a darned good observation, and one I haven't been bitten hard by (yet).

          On the other hand, it's about the best way to prevent coding errors - when it's used well and properly. Oh yes, and tested.

          I've seen projects take weeks long hits when people hand code bit extractions and get it wrong. Thus, my preferred solution is to bit-field map. I know its not absolutely portable, however in my experience, it has been adequate. That's about all I can say.

          Yes, projects that map across architectures have to be much more careful in their structure. That's where guys like you and me come in to "get it right".

          Cheers!

          Comment

          Working...