Logical AND (&) of 2 different bit patterns will give 1 only if both bits have 1. to check ith bit of a number is set or not first Right Shift (<<) 1 to ith position, then AND (&) both the number, if both the bit patterns have 1 at the ith place, the result will be 0.
package org.wesome.dsalgo;
public class CheckIthBitSet {
public static boolean checkIthBitSet(int number, int check) {
int rightShift = (1 << check);
System.out.println(number + " In binary will be " + Integer.toBinaryString(number) + ", 1 right shift up to " + check + " position In binary will be " + Integer.toBinaryString(rightShift));
int result = (number & check);
boolean ithBitSet = (result > 0);
System.out.println("result is " + result + ", " + check + "th bit of " + number + " is set " + ithBitSet);
return ithBitSet;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class CheckIthBitSetTest {
@Test
void checkIthBitSetTest1() {
Assertions.assertFalse(CheckIthBitSet.checkIthBitSet(2, 1));
}
@Test
void checkIthBitSetTest2() {
Assertions.assertTrue(CheckIthBitSet.checkIthBitSet(10, 3));
}
@Test
void checkIthBitSetTest3() {
Assertions.assertTrue(CheckIthBitSet.checkIthBitSet(20, 5));
}
}
plugins {
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}