Solved

Hov do i get bit in integer?

Posted on 2003-11-04
2
1,477 Views
Last Modified: 2008-02-01
Hello

How do I get a specific bit in an integer?

let's say i have the value 123 in an int. That's 1111011 in binary.

How do i get the walue of the the 3rd bit (ie 0) or the 4th bit (ie 1)???
0
Comment
Question by:sk-man
2 Comments
 
LVL 20

Accepted Solution

by:
TheAvenger earned 125 total points
ID: 9677710
Note that this code counts the bits starting from 0, not from 1, so the bits you give as an example are 2 and 3, not 3 and 4

int val = 123;
int bitToTake = 2;

// As a boolean: set/not set
bool bitSet = (val >> bitToTake & 0x01) == 0x01;

// As a number: 1/0
int bit = val >> bitToTake & 0x01;
0
 

Author Comment

by:sk-man
ID: 9686383
Thank you.

It really helped me a lot!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question