Advertisement

Reading the bits of a number...

Started by June 17, 2002 03:49 AM
4 comments, last by Lode 22 years, 6 months ago
I don''t know how newbie this question sounds, my bet is: extremely newbie. Anyway, I''d like to read any of the bits of an integer number, how do I do that? I''d like to make a function ReadABitOfAnIngeter(int integer, int bitPosition) for example ReadABitOfAnIngeter(7,32) should return 1 if my assumption that an int is 32 bits is correct. I''m using C++. Thanks.

  // Note: whichBit is zero-based, LSB first.bool IsBitOn( unsigned whichBit, int number ){return ( ( number & (1 << whichBit ) ) != 0 ) )}  


Does that help? Probably a bit sloppy ''cause I''m just typing this roughly but it should work with minor tweaking.
It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
Advertisement
That helps, thanks

I just KNEW that my question was newbie


And... how can I make a 128-bit integer data type where I can do any mathimatical operations on (especially power)? And of course, read the bits of it?

[edited by - Lode on June 17, 2002 5:04:56 AM]
Well, int isn''t garanteed to be 32 bits, but...


  #include <bitset>std::bitset<32> bits = 7; // initialises with the integer 7bool b = bits[31]; // remember bit numbering goes 0-31  


or, shorter


  #include <bitset>typedef std::bitset<32> bit32_t;bool b = bit32_t(7)[31];  


or if you really want a function


  inline int ReadBit( int integer, size_t pos ){  return (integer >> pos) & 1;}  


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thank you

Did you read the edited part in my post? Is this bitset a way to do a 128 bit integer?
quote: Original post by Lode
And... how can I make a 128-bit integer data type where I can do any mathimatical operations on (especially power)? And of course, read the bits of it?


Use the GNU GMP

Edit: The bitset can be extended to whatever number of bits you need, but the only things you can do with it are boolean operations. Of course, you can reimplement all math operations through boolean ops (the CPU does it), but that's not very efficient.


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on June 17, 2002 5:12:18 AM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement