Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one read an integer bit by bit in Java?

Tags:

java

I would like to take an int as input, and return the kth bit.

int getBit(int n, int k){
    return kth bit in n;
}

How would i do this?

like image 289
user1921187 Avatar asked Jan 03 '13 19:01

user1921187


People also ask

How do I get bits in Java?

Syntax : public static int bitCount(int n) Parameter : n : the value whose bits are to be counted Return : This method returns the count of the number of one-bits in the two's complement binary representation of an int value. Example :To show working of java. lang.

How many bit is an int in Java?

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.

What is bit datatype in Java?

If you want single bits use a boolean and true / false . If you want multi-bit fields you'll have to use an integer type ( byte , short , int or long ) and do the masking yourself.

How do you check if a bit is set or not in Java?

Method 1 (Using Left Shift Operator) 1) Left shift given number 1 by k-1 to create a number that has only set bit as k-th bit. temp = 1 << (k-1) 2) If bitwise AND of n and temp is non-zero, then result is SET else result is NOT SET.


2 Answers

Using bitwise operators:

int getBit(int n, int k) {     return (n >> k) & 1; } 

Explanation (in bits):

n 100010101011101010 (example) n >> 5 000001000101010111 (all bits are moved over 5 spots, therefore &                   the bit you want is at the end) 000000000000000001 (0 means it will always be 0, =                   1 means that it will keep the old value) 1 
like image 58
tckmn Avatar answered Sep 20 '22 17:09

tckmn


return (n >> k) & 1;

Here, n >> k shifts the k-th bit into the least significant position, and & 1 masks out everything else.

like image 45
NPE Avatar answered Sep 18 '22 17:09

NPE