Pergunta

Platfrom 3.5 .Net. (C#)

Por favor, consulte -me ao código que converte ASCII em BCD (C#).

Foi útil?

Solução

O número inteiro armazenará o valor do BCD ... pode ser uma maneira mais limpa, mas isso deve fazer o truque. Mas eu novamente perguntaria por quê?

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 você quiser fazer isso no LINQ (isso não tem limites de verificação) ...

int vs = "12345".ToCharArray().Reverse()
                .Select((c, i) => (c-48) << 4 * i)
                .Sum();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top