Advertisement
Asinka

Binary Digits Count

Nov 4th, 2012
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4.  
  5. class BinaryDigitsCountProgram
  6. {
  7.     static void Main()
  8.     {
  9.         Console.WriteLine("Enter byte 0 or 1 , B = ");
  10.         int b = int.Parse(Console.ReadLine());
  11.         Console.WriteLine("Enter count of number , N = ");
  12.         int n = int.Parse(Console.ReadLine());
  13.         uint bit = 0;
  14.         uint mask = 0;
  15.  
  16.         if (b == 1 || b == 0)
  17.         {
  18.  
  19.             for (int j = 0; j < n; j++)
  20.             {
  21.  
  22.                 Console.WriteLine("Enter number P = ");
  23.                 uint p = uint.Parse(Console.ReadLine());
  24.                 uint count1 = 0;
  25.                 uint count0 = 0;
  26.  
  27.                 for (int i = 0; i < 32; i++)
  28.                 {
  29.  
  30.                     //chacking which bits stay of positions p - 0 or 1
  31.                     mask = (uint)(1 << i);
  32.                     bit = (uint)((p & mask) >> i);
  33.  
  34.                     if (bit == 1) //counting how meny bits are 1
  35.                     {
  36.  
  37.                         count1 = count1 + 1;
  38.                     }
  39.                     else if (bit == 0 && mask < p) //counting how meny bits are 0
  40.                     {
  41.  
  42.                         count0 = count0 + 1;                
  43.                     }
  44.  
  45.                 }
  46.                 if (b == 1)
  47.                 {
  48.                     Console.WriteLine("The number {0} have {1} bytes \"1\"", p, count1);
  49.                 }
  50.                 else
  51.                 {
  52.                     Console.WriteLine("The number {0} have {1} bytes \"0\"", p, count0);
  53.                 }
  54.             }
  55.         }
  56.  
  57.  
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement