Solved

Hov do i get bit in integer?

Posted on 2003-11-04
2
1,453 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Installing IIS after Visual Studio 2015 Community Edition 5 46
How to iterate over object and get property name and value 4 26
What is Thread.Sleep? 5 45
Class object 2 26
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

930 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now