Domanda

Platfrom 3.5 .net. (c #)

per favore, mi riferisca al codice che converte ascii in bcd (c #).

È stato utile?

Soluzione

il numero intero memorizzerà il valore BCD ... potrebbe essere un modo più pulito ma questo dovrebbe fare il trucco. Ma vorrei chiedere di nuovo perché?

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

... se vuoi farlo in LINQ (questo non ha controllo dei limiti) ...

int vs = "12345".ToCharArray().Reverse()
                .Select((c, i) => (c-48) << 4 * i)
                .Sum();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top