By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,093 Members | 1,429 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,093 IT Pros & Developers. It's quick & easy.

How to access the individual bits of a value stored?

P: 1
how to access the bits of a value stored in memory as such?
Sep 27 '10 #1
Share this Question
Share on Google+
4 Replies

Expert 100+
P: 542
you may like to see bitwise operators in C/C++
Sep 27 '10 #2

Expert 100+
P: 983
Either that, or you can use a union to map a bitmaped structure on top of your input value, like so:

Expand|Select|Wrap|Line Numbers
  2. union myConverter
  3. {
  4.   long  baseValue
  5.   struct
  6.   {
  7.     unsigned  bit0 : 1;
  8.     unsigned  bit1 : 1;
  9.     unsigned  bits2to31 : 30;
  10.   };
  11. } convert;
  13. convert.baseValue = 12345;
  14. convert.bit0 = 0;                // baseValue now = 12344
Sep 27 '10 #3

Expert Mod 5K+
P: 8,950
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.
Sep 27 '10 #4

Expert 100+
P: 983

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".

Sep 27 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.