Solved

Hov do i get bit in integer?

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

747 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

12 Experts available now in Live!

Get 1:1 Help Now