1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

C++ Bit Counting Problem

Discussion in 'Software Development' started by Daskill, Nov 15, 2008.

Thread Status:
Not open for further replies.
Advertisement
  1. Daskill

    Daskill Thread Starter

    Joined:
    Oct 17, 2007
    Messages:
    295
    I've got to implement a function that will return the value of bit n of a binary number. I then have to implement a function that will change bit n to 1 or return a 0 if it is out of range.

    I'm a bit stuck on this one, anyone know how I'd do it?
     
  2. mt2002

    mt2002

    Joined:
    Sep 14, 2005
    Messages:
    918
    C++ bitwise operators tutorial

    To get what you want you should read up on bit masks and the bitwise and operator. The basic idea is to mask out the bits that you dont want by using a bitwise and operator. I can post example code if you like.
     
  3. Daskill

    Daskill Thread Starter

    Joined:
    Oct 17, 2007
    Messages:
    295
    That might be helpful if you wouldn't mind.
     
  4. mt2002

    mt2002

    Joined:
    Sep 14, 2005
    Messages:
    918
    Something like this?
    Code:
    inline int get_bit (const int value, const int bit) {
    
    	int ret = value & (1 <<  ( bit-1 ) );
    
    	return ret ? 1 : 0;
    }
    This will return a 1 if the bit is set, 0 if it is not.
     
As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/769715

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice