Advertisement
dimipan80

3.14 Modify Bit At Given Position In Integer Number

Jun 5th, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 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 (a few lines of C# code) 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. */
  2.  
  3. namespace _14.ModifyBitAtGivenPositionInIntegerNumber
  4. {
  5.     using System;
  6.  
  7.     public class ModifyBitAtGivenPositionInIntegerNumber
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             checked
  12.             {
  13.                 Console.Write("Enter a whole non-negative number: ");
  14.                 uint num = uint.Parse(Console.ReadLine());
  15.                 int positionP;
  16.                 do
  17.                 {
  18.                     Console.Write("Enter index for Bit position: ");
  19.                 }
  20.                 while (!int.TryParse(Console.ReadLine(), out positionP) || positionP < 0 || positionP > 31);
  21.  
  22.                 int bitValueToModified;
  23.                 do
  24.                 {
  25.                     Console.Write("Enter value of bit on position P, to modifying: ");
  26.                 }
  27.                 while (!int.TryParse(Console.ReadLine(), out bitValueToModified) || bitValueToModified < 0 || bitValueToModified > 1);
  28.  
  29.                 // Checking on given position in number bit value:
  30.                 int startBitValue = (int)((long)num >> positionP) & 1;
  31.  
  32.                 // Comparing founded bit value and given is equals or not. If bit values is equals, modifying is not necesary and given number is output result.
  33.                 uint resultNum = num;
  34.                 if (startBitValue != bitValueToModified)
  35.                 {
  36.                     long bitMask;
  37.                     if (startBitValue == 0)
  38.                     {
  39.                         // Modifying bit value on given position from 0 to 1:
  40.                         bitMask = 1 << positionP;
  41.                         resultNum = (uint)((long)num | bitMask);
  42.                     }
  43.                     else
  44.                     {
  45.                         // Modifying bit value on given position from 1 to 0:
  46.                         bitMask = ~(1 << positionP);
  47.                         resultNum = (uint)(num & bitMask);
  48.                     }
  49.                 }
  50.  
  51.                 Console.WriteLine("The number after modifying bit value is: {0} !", resultNum);
  52.             }
  53.         }        
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement