Advertisement
dimipan80

Modify a Bit at Given Position

Aug 5th, 2014
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. /* We are given an integer number n, a bit value v (v=0 or 1) and a position p. Write a sequence of operators
  2.  * 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. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class SetBitAtGivenPositionInGivenIntegerToGivenBitValue {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a Integer number: ");
  12.         long number = scan.nextLong();
  13.         System.out.print("Enter whole number for Bit position: ");
  14.         int bitP = scan.nextInt();
  15.         System.out.print("Enter value to set Bit '0' or '1' : ");
  16.         int givenBitValue = scan.nextInt();
  17.         scan.close();
  18.  
  19.         if (bitP >= 0 && bitP <= 31 && (givenBitValue == 0 || givenBitValue == 1)) {
  20.             long bitMask = (long)1 << bitP;
  21.             int currentBitValue = ((number & bitMask) == 0) ? 0 : 1;
  22.             if (currentBitValue != givenBitValue) {
  23.                 number ^= bitMask;
  24.             }
  25.  
  26.             System.out.printf("The Number after Bit Modification is: %d !\n", number);
  27.  
  28.         } else {
  29.             System.out.println("Error! - One or more of Input arguments is Out of Range!!!");
  30.         }
  31.     }
  32.  
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement