math conversions

M

MikeJ

Hello,
Are there any classes that do the conversions from
hex2Dec(), dec2Hex()

decimal, hex, octal ..and back to a Base
or do i have to implement them myself based
on existing conversion utilities in Net

Thanks
MJ
 
D

David R. Longnecker

Mike-

I'm not sure about an actual method for it, but Hex-> Dec, you can use the
Int32.Parse method.

string hexString = "000a01af";
int intOutput = Int32.Parse(hexString, NumberStyles.HexNumber);

NumberStyles is part of the System.Globalization namespace.

For Dec -> Hex, a String.Format should work in most cases (using integer
from above) :

UInt32 unicodeInt = Convert.ToUInt32(intOutput);
string hexOutput = String.Format("{0:x2}", unicodeInt);

Octal and others... I'm not sure, but I'd assume _someone_ has come up with
the libraries or at least has posted the source code somewhere.

HTH.

-dl

--
David R. Longnecker
http://blog.tiredstudent.com

M> Hello,
M> Are there any classes that do the conversions from
M> hex2Dec(), dec2Hex()
M> decimal, hex, octal ..and back to a Base
M> or do i have to implement them myself based
M> on existing conversion utilities in Net
M> Thanks
M> MJ
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

MikeJ said:
Are there any classes that do the conversions from
hex2Dec(), dec2Hex()

decimal, hex, octal ..and back to a Base
or do i have to implement them myself based
on existing conversion utilities in Net

A very general approach:

private static string DIGITS = "0123456789ABCDEF";
private static int FromAny(string s, int radix)
{
int res = 0;
char[] sa = s.ToCharArray();
for (int i = 0; i < s.Length; i++) {
res = res * radix + DIGITS.IndexOf(sa);
}
return res;
}
private static string ToAny(int i, int radix)
{
string res = "";
int tmp = i;
while (tmp > 0) {
res = DIGITS.ToCharArray()[tmp % radix] + res;
tmp = tmp / radix;
}
return res;
}
public static int FromDec(string s)
{
return FromAny(s, 10);
}
public static string ToDec(int i)
{
return ToAny(i, 10);
}
public static int FromHex(string s)
{
return FromAny(s, 16);
}
public static string ToHex(int i)
{
return ToAny(i, 16);
}
public static int FromBin(string s)
{
return FromAny(s, 2);
}
public static string ToBin(int i)
{
return ToAny(i, 2);
}

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top