fbinnzhivko

05.01 BitsUp

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