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?
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.
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.
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.
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.
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
return (n >> k) & 1;
Here, n >> k
shifts the k
-th bit into the least significant position, and & 1
masks out everything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With