By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,557 Members | 1,416 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,557 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


ashitpro
Expert 100+
P: 542
you may like to see bitwise operators in C/C++

http://www.cs.cf.ac.uk/Dave/C/node13.html
Sep 27 '10 #2

Oralloy
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
  1.  
  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;
  12.  
  13. convert.baseValue = 12345;
  14. convert.bit0 = 0;                // baseValue now = 12344
  15.  
Sep 27 '10 #3

Banfa
Expert Mod 5K+
P: 8,916
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

Oralloy
Expert 100+
P: 983
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!
Sep 27 '10 #5

Post your reply

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