Wednesday, September 23, 2009

Some useful code in C# - Part 2

I had posted some C# programs written by my wife . The reason for those code was to learn more about Bit level programming. One of my friend pointed out couple of mistakes in the code and i passed on the message to her. Here is the result of that

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitManipulation2
{
public class BitUtils
{
///
///
///

///
///
public static string ConvertIntToBit(int x)
{
int y = x;

string n = "";
while (y != 0)
{
if (y % 2 == 0)
n = '0' + n;
else
n = '1'+ n;

y = y >> 1;

}
return n;
}
///
///
///

///
///

public static int ConvertBitToInt(string x)
{
int z = x.Length-1;
int i = 0;
int n = 0;
int y = 0;
for (; i <= z; i++ )
{
if (x[i] == '0')
y = 0;
else if (x[i] == '1')
y = 1;
n = (y * (int)Math.Pow(2, i)) + n;
}
return n;
}

///
///
///

///
///
public static string ConvertIntToHex(int x)
{
int y = x;
string z = "";
while (y != 0)
{
int a = y % 16;
if (a >= 0 && a <= 9)
z = a + z;
else
{
int c = a - 10;
char b = Convert.ToChar( 'A' +c);

z = b + z;
}

y = y >> 4;
}

return z;
}

public static int ConvertHexToInt(string x)
{
int n = 0;
int z = 0;
int i = x.Length-1;
foreach (char y in x )
{
if (y >= '0' && y <= '9')
n = y - '0';
else if (y >= 'A' && y <= 'F')
n = 10 + (y - 'A');

z = (int)((n*Math.Pow(16, i)) + z);
i--;
}
return z;
}


/////////////////
//
// Test driver program

static void Main(string[] args)
{


string z = BitUtils.ConvertIntToBit(32);
Console.WriteLine(z);

int a = BitUtils.ConvertBitToInt("1001");
Console.WriteLine(a);

string x = BitUtils.ConvertIntToHex(365);
Console.WriteLine(x);

int b = BitUtils.ConvertHexToInt("A5");
Console.WriteLine(b);
Console.Read();
}

}
}

0 comments: