Thread: Reading bits

  1. #1
    Registered User
    Join Date
    Jul 2010

    Reading bits

    How can I read the bit number 30 of an 32-bit interger?

    I've tried the following:
    int lp = msg->lParam;
    lp <<= 29;
    if(lp & 1)
    {.....} // bit number 30 is 1
    {...} //bit number 30 is 0
    but is doesn't work.

    Thanks in advance!

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Toronto, ON
    You don't need to shift any bits. Just mask the bit you're looking for:
    if ( lp & 0x02000000 )
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  3. #3
    Registered User
    Join Date
    Jul 2010
    Ok, thanks for help.

    But are you sure this checks the 30th bit of a DWORD? To make it more clear what i'm trying to do see here(in the remarks section, second paragraph).
    Last edited by Phenom; 07-05-2010 at 12:47 PM.

  4. #4
    Join Date
    Oct 2007
    Inside my computer
    No, there's a zero too few.
    00100000 00000000 00000000 00000000 in hexadecimal is: 0x20000000
    Hence, that is the mask you are looking for.

    If this is of any help, I have a small utility class that may help you here:
    You basically just create a Stuff::Bit and pass the lParam into the constructor, then you can use the index operator to check if a particular bit is set.
    You can also set and clear bits.
    Last edited by Elysia; 07-05-2010 at 02:24 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Jul 2010
    I'll try your class, but I have found a way to do what I want without all this bit stuff, although it's more complicated.

    I guess it's up to me now. Thanks everyone for help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Working with bits and SHA-1
    By Desolation in forum C++ Programming
    Replies: 6
    Last Post: 12-28-2008, 01:34 AM
  2. merging bits
    By Drac in forum C++ Programming
    Replies: 8
    Last Post: 12-21-2008, 06:13 PM
  3. SDLKey to ASCII without unicode support?
    By zacs7 in forum Game Programming
    Replies: 6
    Last Post: 10-07-2007, 03:03 AM
  4. Replies: 7
    Last Post: 08-19-2007, 08:10 AM
  5. packing and unpacking bits
    By soonerfan in forum C Programming
    Replies: 1
    Last Post: 12-11-2001, 09:40 AM