views:

287

answers:

1

Platfrom 3.5 .net.(c#)

please refer me to code which converts ascii to bcd (c#).

+3  A: 

the integer num will store the BCD value... might be a cleaner way but this should do the trick. But I again would ask why?

char[] str = "12345".ToCharArray();
int num = 0;
for (int i = 0; i < str.Length; i++)
{
    var val = str[str.Length -1 - i] - 48;
    if (val < 0 || val > 9) 
        throw new ArgumentOutOfRangeException();
    num += val << (4 * i);
}

Console.WriteLine(num.ToString("x2")); //must be viewed as hex

... if you want to do it in LINQ (this does not have bounds checking) ...

int vs = "12345".ToCharArray().Reverse()
                .Select((c, i) => (c-48) << 4 * i)
                .Sum();
Matthew Whited