Tuesday, September 22, 2009

Some useful code in C#

To get a grip on Binary numbers and Hexadecimal numbers , my wife wrote couple of programs today. I thought , it will be useful for some one out there. The Programs are not meant to be efficient. It has been written with learning in mind.

Note :- Since i do not know how to esacpe Pipe character...i have converted the code into if model of coding... ( The code contain some minor errors and has been superceded by the following post... available here )




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BitManipulation
{
public class BitUtils
{
///
///
///

///
///
public static string ConvertIntToBit(int x)
{
int y = x;
string n = "";
while (y != 0)
{
if (y % 2 == 0)
n = n + "0";
else
n = n + "1";
y = y >> 1;
}
return n;
}
///
///
///

///
///
public static bool isBitString(string x)
{
foreach (char y in x)
{
if (y == '1')
continue;
else if (y == '0')
continue;
return false;
}
return true;
}
///
///
///

///
///
public static int ConvertBitToInt(string x)
{
int z = 0;
int a = 0;
int i = (x.Length-1);
foreach (char y in x)
{
if (y == '1')
{
z = 1;
}
else if (y == '0')
{
z = 0;
}
a = a +( z*(int)Math.Pow(2, i));
i--;
}
return a;
}
///
///
///

///
///
public static string ConvertIntToHex(int x)
{
int y = x;
string n = "";
while (y != 0)
{
int a = y %16;
if ((a >= 0) && a <= 9) { n = a.ToString()+n; } else { switch (a) { case 10: n = "A"+n; break; case 11: n = "B"+n; break; case 12: n = "C"+n; break; case 13 : n = "D"+n; break; case 14: n = "E"+n; break; case 15: n = "F"+n; break; } } y = y >> 4;
}
return (n);
}
///
///
///

///
///
public static string StringReverse(string x)
{
string a = "";
foreach (char y in x)
{
a = y + a;
}
return a;
}
///
///
///

///
///
public static bool IsHexString(string x)
{
foreach (char y in x)
{
if ((y >= '0' && y <= '9')) { continue; } else if ( (y >= 'A' && y <= 'F')) continue; return false; } return true; } public static int ConvertHexToInt(string x) { int z=0; int a = 0; int i = x.Length-1; foreach (char y in x.ToCharArray() ) { if (y >= '0' && y <= '9') { z = y-'0'; } else if (y >= 'A' && y <= 'F')
{
z = 15-('F' - y) ;
}
a = a+((z*(int)Math.Pow(16, i))) ;
i--;
}
return a;
}

static void Main(string[] args)
{
string s = "65";
int x = Int32.Parse(s);
string a=BitUtils.ConvertIntToBit(x);
Console.WriteLine(a);

if (BitUtils.isBitString("101001"))
{
Console.WriteLine("Valid bit string");

}
int z = BitUtils.ConvertBitToInt("1001");
Console.WriteLine(z);
string c = BitUtils.ConvertIntToHex(65);
Console.WriteLine(c);
if (BitUtils.IsHexString("FFFG"))
{
Console.Write("Valid HexaDecimal");
}
int y = BitUtils.ConvertHexToInt("FF");
Console.WriteLine(y);
Console.Read();
}

}
}

0 comments: