|
| 1 | +import java.util.*; |
| 2 | +public class Main |
| 3 | +{ |
| 4 | + static Scanner sc=new Scanner(System.in); |
| 5 | + public static void getbit(int pos,int num){ |
| 6 | + /* Bit Mask : 1<<i |
| 7 | + Operation :AND : |
| 8 | + */ |
| 9 | + int bitmask= 1<<pos; |
| 10 | + int temp=(num & bitmask); |
| 11 | + if(temp==0) System.out.println("Bit at position "+ pos +" is 0"); |
| 12 | + else System.out.println("Bit at position "+ pos +" is 1"); |
| 13 | + |
| 14 | + } |
| 15 | + public static void setbit(int pos,int num){ |
| 16 | + /* |
| 17 | + Bit Mask : 1<<i |
| 18 | + Operation :OR : |
| 19 | + */ |
| 20 | + int bitmask=1<<pos; |
| 21 | + int temp=(num | bitmask); |
| 22 | + System.out.println("New number is "+temp); |
| 23 | + } |
| 24 | + public static void clearbit(int pos,int num){ |
| 25 | + /* |
| 26 | + Bit Mask : 1<< i |
| 27 | + Operation : AND WITH NOT |
| 28 | + */ |
| 29 | + int bitmask=1<<pos; |
| 30 | + bitmask=~(bitmask); |
| 31 | + int temp=(num & bitmask); |
| 32 | + System.out.println("After performing clear bit number is: "+temp); |
| 33 | + } |
| 34 | + public static void updatebit(int pos,int num){ |
| 35 | + /* |
| 36 | + For 0 For 1 |
| 37 | + Bitmask : 1<<i Bitmask: 1<<i |
| 38 | + Operation :AND WITH NOT Operation : OR |
| 39 | + */ |
| 40 | + int ch=sc.nextInt(); |
| 41 | + if(ch==1){ // for updating 1 |
| 42 | + int bitmask=1<<pos; |
| 43 | + int temp=(num | bitmask); |
| 44 | + System.out.println("New number is "+temp); |
| 45 | + } |
| 46 | + else // for updating 0 |
| 47 | + { |
| 48 | + int bitmask=1<<pos; |
| 49 | + bitmask=~(bitmask); |
| 50 | + int temp=(num & bitmask); |
| 51 | + System.out.println("After performing updatebit number is: "+temp); |
| 52 | + } |
| 53 | + } |
| 54 | + public static void main(String[] args) { |
| 55 | + System.out.println("Enter the position of the bit that you want to:"); |
| 56 | + int pos=sc.nextInt(); |
| 57 | + System.out.println("Enter the number:"); |
| 58 | + int num=sc.nextInt(); |
| 59 | + System.out.println("Enter 1 for get bit:"); |
| 60 | + System.out.println("Enter 2 for set bit:"); |
| 61 | + System.out.println("Enter 3 for clear bit:"); |
| 62 | + System.out.println("Enter 4 for updatebit:"); |
| 63 | + int ch=sc.nextInt(); |
| 64 | + switch(ch){ |
| 65 | + case 1: getbit(pos,num); |
| 66 | + break; |
| 67 | + case 2: setbit(pos,num); |
| 68 | + break; |
| 69 | + case 3: clearbit(pos,num); |
| 70 | + break; |
| 71 | + case 4: updatebit(pos,num); |
| 72 | + break; |
| 73 | + default : |
| 74 | + System.out.println("enter correct choice:"); |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | + } |
| 79 | +} |
0 commit comments