Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* We are given an integer number n, a bit value v (v=0 or 1) and a position p. Write a sequence of operators
- * that modifies n to hold the value v at the position p from the binary representation of n while preserving all other bits in n. */
- import java.util.Scanner;
- public class SetBitAtGivenPositionInGivenIntegerToGivenBitValue {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a Integer number: ");
- long number = scan.nextLong();
- System.out.print("Enter whole number for Bit position: ");
- int bitP = scan.nextInt();
- System.out.print("Enter value to set Bit '0' or '1' : ");
- int givenBitValue = scan.nextInt();
- scan.close();
- if (bitP >= 0 && bitP <= 31 && (givenBitValue == 0 || givenBitValue == 1)) {
- long bitMask = (long)1 << bitP;
- int currentBitValue = ((number & bitMask) == 0) ? 0 : 1;
- if (currentBitValue != givenBitValue) {
- number ^= bitMask;
- }
- System.out.printf("The Number after Bit Modification is: %d !\n", number);
- } else {
- System.out.println("Error! - One or more of Input arguments is Out of Range!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement