Advertisement
sholev

CatchTheBits

Jul 17th, 2015
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2.  
  3. class CatchTheBits
  4. {
  5.     static void Main()
  6.     {
  7.         int numberOfBytes = Int32.Parse(Console.ReadLine());
  8.         int position = Int32.Parse(Console.ReadLine());
  9.         int[] bytes = new Int32[numberOfBytes];
  10.  
  11.         for (int i = 0; i < bytes.Length; i++)
  12.             bytes[i] = Int32.Parse(Console.ReadLine());
  13.  
  14.  
  15.         int index = 1;
  16.         int result = 0;
  17.         int shifts = 0;
  18.  
  19.         for (int i = 0; i < bytes.Length; i++)
  20.             for (int l = 0; l < 8; l++)
  21.                 if (index == l + (i * 8))
  22.                 {
  23.                     result = result << 1;
  24.                     shifts++;
  25.                     result = SetBitAtPosition(result, 0, GetBitAtPosition(bytes[i], 7 - l));
  26.                     if (shifts == 8)
  27.                     {
  28.                         shifts = 0;
  29.                         Console.WriteLine(result);
  30.                         result = 0;
  31.                     }
  32.                     index += position;
  33.                 }
  34. //        if (result != 0)        
  35.         Console.WriteLine(result << (8 - shifts));
  36.     }
  37.  
  38.     private static int GetBitAtPosition(int number, int position)
  39.     {
  40.         return (number >> position) & 1;
  41.     }
  42.  
  43.     private static int SetBitAtPosition(int number, int position, int setBitTo)
  44.     {
  45.         if (setBitTo == 1)
  46.             return number | (1 << position);
  47.         else
  48.             return number & ~(1 << position);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement