public class Convertor
{
public Convertor()
{
string[] all = {"0","1","2","3","4","5","6","7","8","9","a",
"b","c","d","e","f","g","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x",
"y","z"};
this.data = all;
}
public string ConvertFrom10(int number, int numSystem)
{
string result = "";
int remains = number;
if (numSystem < 2)
numSystem = 2;
if (numSystem > 36)
numSystem = 36;
do
{
int toAdd = remains % numSystem;
result = this.data[toAdd] + result;
remains -= toAdd;
remains /= numSystem;
} while (remains > 0);
return result;
}
public string ConvertFrom10(int number, int numSystem,
bool uppercase)
{
string result = ConvertFrom10(number, numSystem);
if (uppercase == true)
return result.ToUpper();
else
return result.ToLower();
}
public int ConvertTo10(string number, int numSystem)
{
int result = 0;
int multiplier = 1;
number = number.ToLower();
for (int i = number.Length - 1; i >= 0; i--)
{
result += (this.getIndex(number[i].ToString()) *
multiplier);
multiplier *= numSystem;
}
return result;
}
int getIndex(string item)
{
for (int i = 0; i < this.data.Length; i++)
{
if (this.data[i] == item)
return i;
}
throw (new Exception("Can't find the item \"" + item +
"\" in the conversion array"));
}
string[] data;
}
2011/2/16 Antony <[email protected]>
> Hi everybody,
> I have to convert a string (mem) into binary code. Example:
> 1234A --> 00010010001101001010
>
> I wrote this code, but doesn't work:
>
> string binary = "";
> for (int i = 0; i < mem.Length; i++)
> {
> string s = mem.Substring(i,1);
> binaryString += hex2binary(s);
> }
>
> string hex2binary(string hexvalue)
> {
> string binaryval = "";
> string tmp = Convert.ToString(Convert.ToInt32(hexvalue,
> 16), 2);
> binaryval = String.Format("{0:X4}", tmp);
> return binaryval;
> }
>
> Thanks for reply!