0

Platfrom 3.5 .net.(c#)

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

Maddy.Shik
  • 6,609
  • 18
  • 69
  • 98
  • 3
    BCD is only useful for storing numbers. Why do you want to convert ACSII to BCD? – Matthew Whited Nov 30 '09 at 15:40
  • I hate it when people answer questions with another question. He wants to convert ASCII to BCD because he wants to. – Gabriel Magana Nov 30 '09 at 16:11
  • I just wanted to point out that BCD only encodes number for someone that might expect to be able to encode all of ASCII into BCD. He may also want to convert from normal numerical (hex) to BCD yet stated the question wrong. There is a reason to ask for more details. – Matthew Whited Nov 30 '09 at 18:09
  • I need to do it to retrieve encryption key from 16 bytes data to 8 bytes by ascii to bcd conversion. – Maddy.Shik Dec 01 '09 at 07:16
  • That's cool. I had to work with BCD conversion to talk with a real time clock with a .Net Micro Framework project. (encoding dates as BCD from DateTime values was fun) I just wanted to make sure you were getting the answer you expected. Thanks and good luck. – Matthew Whited Dec 01 '09 at 14:56

1 Answers1

2

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
  • 22,160
  • 4
  • 52
  • 69