0% found this document useful (0 votes)
7 views3 pages

Java Bit Manipulation AC

The document provides an introduction to bit manipulation in Java, including methods to get, set, clear, and update bits in an integer. It includes code examples demonstrating each operation using bitwise operators. Additionally, it lists homework problems related to bit manipulation and number system conversions.

Uploaded by

l5jz0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Java Bit Manipulation AC

The document provides an introduction to bit manipulation in Java, including methods to get, set, clear, and update bits in an integer. It includes code examples demonstrating each operation using bitwise operators. Additionally, it lists homework problems related to bit manipulation and number system conversions.

Uploaded by

l5jz0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java - Introduction to Programming

Lecture 14

Bit Manipulation

Get Bit
import java.util.*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 3;
int bitMask = 1<<pos;

if((bitMask & n) == 0) {
System.out.println("bit was zero");
} else {
System.out.println("bit was one");
}
}
}

Set Bit
import java.util.*;

public class Bits {


public static void main(String args[]) {
int n = 5; //0101
int pos = 1;
int bitMask = 1<<pos;

int newNumber = bitMask | n;


System.out.println(newNumber);
}
}

Apna College
Clear Bit
import java.util.*;
public class Bits {
public static void main(String args[]) {
int n = 5; //0101
int pos = 2;
int bitMask = 1<<pos;
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
System.out.println(newNumber);
}
}

Update Bit

import java.util.*;

public class Bits {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int oper = sc.nextInt();
// oper=1 -> set; oper=0 -> clear
int n = 5;
int pos = 1;

int bitMask = 1<<pos;


if(oper == 1) {
//set
int newNumber = bitMask | n;
System.out.println(newNumber);
} else {
//clear
int newBitMask = ~(bitMask);
int newNumber = newBitMask & n;
System.out.println(newNumber);
}

}
}

Apna College
Homework Problems
1.​ Write a program to find if a number is a power of 2 or not.
2.​ Write a program to toggle a bit a position = “pos” in a number “n”.
3.​ Write a program to count the number of 1’s in a binary representation
of the number.
4.​ Write 2 functions => decimalToBinary() & binaryToDecimal() to convert
a number from one number system to another. [BONUS]

Apna College

You might also like