ADVERTISEMENT
ADVERTISEMENT

Java program to SET and CLEAR bits of the given number

Given/input an integer number, we have to SET and CLEAR its bits.
Submitted by Nidhi, on March 07, 2022

Problem Solution:

In this program, we will create an integer variable and then we will set and clear the bits of the number using bitwise operators.

Program/Source Code:

The source code to SET and CLEAR bits of the given number is given below. The given program is compiled and executed successfully.

// Java program to SET and CLEAR bits 
// of the given number

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int num = 0x0;

    //set 0th bit
    num |= (1 << 0);

    //set 1st bit
    num |= (1 << 1);

    System.out.printf("Number after setting 0th and 1st bits: %d\n", num);

    //Clear 0th bit
    num &= ~(1 << 0);

    //Clear 1st bit
    num &= ~(1 << 1);

    System.out.printf("Number after clearing 0th and 1st bits: %d\n", num);
  }
}

Output:

Number after setting 0th and 1st bits: 3
Number after clearing 0th and 1st bits: 0

Explanation:

In the above program, we created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we created an integer variable initialized with 0x0. Then we set and cleared bits of the created variable using bitwise operators.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.