0

Possible Duplicate:
Java: Checking if a bit is 0 or 1 in a long

I want to return the x'th bit of n. Bit 0 is least significant bit. i need a method like public static int getBit(int n, int i) that get n and return the i'th bit.

Community
  • 1
  • 1
parsa
  • 49
  • 6

2 Answers2

1

Do you mean?

 public static int getBit(int n, int i) {
     return (n >>> i) & 1
 }

or as @harold suggests

 n & (1L << x)
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1
return (1L << x) & n;

should work just fine.

Zéychin
  • 4,135
  • 2
  • 28
  • 27