Advertisement
Guest User

Bits Up

a guest
Mar 26th, 2015
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. class BitsUp
  4. {
  5.     static void Main()
  6.     {
  7.     // input
  8.         int n = int.Parse(Console.ReadLine());
  9.  
  10.         int step = int.Parse(Console.ReadLine());
  11.  
  12.         int number = 0;
  13.  
  14.         // StringBuilder binaries will be storing the binary representation of all n numbers
  15.         StringBuilder binaries = new StringBuilder();
  16.  
  17.         // for all n numbers read from the console
  18.         for (int i = 0; i < n; i++)
  19.         {
  20.             number = int.Parse(Console.ReadLine()); // read the number
  21.             string bin = Convert.ToString(number, 2).PadLeft(8, '0'); // convert the number to a binary string
  22.             binaries.Append(bin); // append the above binary string to StringBuilder binaries
  23.         }
  24.         // Console.WriteLine(binaries);  // uncomment if you want to see the binary representations of all n numbers combined in one string
  25.  
  26.     // logic
  27.         for (int j = 0; j < binaries.Length; j++)
  28.         {
  29.             // set to 1 the bits at positions: 1, 1 + step, 1 + 2*step, ...
  30.             // if step = 1, 1 % 1 = 0, so the first condition won't help, and we also need the second one
  31.             if (j % step == 1 || (step == 1 && j > 0))
  32.             {
  33.                 binaries[j] = '1';
  34.             }
  35.         }
  36.         // Console.WriteLine(binaries); // uncomment if you want to see the upped bits at the required positions (the ammended StringBuilder binaries)
  37.  
  38.         // converting the above StringBuilder binary into an array of final int numbers
  39.         int[] numbers = new int[n]; // here we will be storing the final int numbers
  40.         int index = 0;
  41.         string temp = binaries.ToString(); // converting StringBuilder binaries to string
  42.         for (int k = 0; k < binaries.Length; k += 8)
  43.         {
  44.             string sub = temp.Substring(k, 8); // splitting the temp string into 8-chars substrings
  45.             numbers[index] = Convert.ToInt32(sub, 2 ); // converting the substrings into int numbers
  46.             index++;
  47.         }
  48.  
  49.     // printing the final int numbers
  50.         for (int l = 0; l < n; l++)
  51.         {
  52.             Console.WriteLine(numbers[l]);
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement