Thursday, April 30, 2009

Get the N-th Bit value of any Integer number

Share at Facebook

Once again bitwise operations guys. This time we'll know about finding the nth bit value of any 31 bit positive integer number. For example you have a number 120, and you want to get the 7th bit of the number. Here is a function in C/C++ code. But you can convert the code into Perl/Python/Java/PHP/Ruby or whatever you want. The basic is the same.

The bit position are start from left to right.

* Function takes the decimal number
* Function takes the Nth bit (1 to 31)
* Return the value of Nth bit from decimal
int get_bit(int decimal, int N){

// Shifting the 1 for N-1 bits
int constant = 1 << (N-1);

// if the bit is set, return 1
if( decimal & constant ){
return 1;

// If the bit is not set, return 0
return 0;

The above function will take a 31 bit integer number, and the second parameter is the N(1 to 31), means which position you are interested. Here is few example code to use the function

printf("%d\n", get_bit(3,1));
printf("%d\n", get_bit(12100,7));
printf("%d\n", get_bit(12731273,29));
printf("%d\n", get_bit(2111823716,18));

The output will be:

1st bit value of 3 is = 1
7th bit value of 12100 is = 1
29th bit value of 12731273 is = 0
18th bit value of 2111823716 is = 1

Bit-wise operations are fun to use, and faster too. The example is I've given is very basic, and the syntax will work for almost every programming languages. So you can convert the tiny C/C++ code into others. I'll appreciate if anyone convert that into other language, and post as a comment here.


T_Rose said...


def get_bit(decimal, N):
return (decimal >> N) & 1

Anonymous said...

this post is very helpful. Thank you.

Anonymous said...

For the sake of completeness (and because this turns up pretty high on google rankings);

Why do you restrict your index to 1 to 31? Aren't you interested in the 32nd bit also?

This should either read 1 to 32 or you could use
a 0-based index (as C does) and make this 0 to 31.

Lukas Majchrak said...

in java it could be:
public int getBit(int decimal, int bitAt)
int constant = 1 << (bitAt);
return (decimal & constant)>0 ? 1 : 0;

Anonymous said...

The MSB is the sign bit.