Побитовые операции - сдвиг - C#
Формулировка задачи:
Вот код. Объясните пожалуйста,почему так ведёт себя последний цикл. Как-то он странно сдвигает.
/*
* Created by SharpDevelop.
* User: User
* Date: 12.02.2016
* Time: 21:05
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Bit
{
class Program
{
public static void Main(string[] args)
{
int a,b,i,count=0,h;
int [] m = new int[40];
a=Convert.ToInt32(Console.ReadLine());
Array.Resize(ref m,10);
b=a;
h=a;
while (b!=0)
{
b/=2;
count++;
}
Array.Resize(ref m,count);
for (i=0;i<m.Length;i++)
{
if ((a%2==0)&(a>0))
{
m[i]=a%2;
a/=2;
}
else if((a%2!=0)&(a>0))
{
m[i]=1;
a/=2;
}
}
for (i=0;i<m.Length;i++)
Console.Write(m[m.Length-i-1]);
Console.WriteLine();
a=h;
b=a<<1;
Console.WriteLine(b);
Console.WriteLine();
for (i=0;i<m.Length;i++)
{
if ((b%2==0)&(b>0))
{
m[i]=b%2;
b/=2;
}
else if((b%2!=0)&(b>0))
{
m[i]=1;
b/=2;
}
}
for (i=0;i<m.Length;i++)
Console.Write(m[m.Length-i-1]);
Console.WriteLine();
b=a<<2;
for (i=0;i<m.Length;i++)
{
if ((b%2==0)&(b>0))
{
m[i]=b%2;
b/=2;
}
else if((b%2!=0)&(b>0))
{
m[i]=1;
b/=2;
}
}
for (i=0;i<m.Length;i++)
Console.Write(m[m.Length-i-1]);
Console.WriteLine();
b=a>>1;
for (i=0;i<m.Length;i++)
{
if ((b%2==0)&(b>0))
{
m[i]=b%2;
b/=2;
}
else if((b%2!=0)&(b>0))
{
m[i]=1;
b/=2;
}
}
for (i=0;i<m.Length;i++)
Console.Write(m[m.Length-i-1]);
Console.WriteLine();
// TODO: Implement Functionality Here
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}Решение задачи: «Побитовые операции - сдвиг»
textual
Листинг программы
using System;
namespace Bit
{
class Program
{
public static void Main(string[] args)
{
Console.Write("a = ");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} ({1})\n", Convert.ToString(a, 2), a);
int b = a << 1;
Console.WriteLine("a << 1");
Console.WriteLine("{0} ({1})\n", Convert.ToString(b, 2), b);
b = a << 2;
Console.WriteLine("a << 2");
Console.WriteLine("{0} ({1})\n", Convert.ToString(b, 2), b);
b = a >> 1;
Console.WriteLine("a >> 1");
Console.WriteLine("{0} ({1})\n", Convert.ToString(b, 2), b);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}