Frage

Ich möchte einen int zu einem Byte [2] Array mit BCD konvertieren.

Die int in Frage kommen von Datetime das Jahr darstellen und muss zwei Bytes umgewandelt werden.

Gibt es eine vorgefertigte Funktion, die dies tut oder können Sie mir eine einfache Möglichkeit, dies zu tun?

Beispiel:

int year = 2010

ausgeben würde:

byte[2]{0x20, 0x10};
War es hilfreich?

Lösung

    static byte[] Year2Bcd(int year) {
        if (year < 0 || year > 9999) throw new ArgumentException();
        int bcd = 0;
        for (int digit = 0; digit < 4; ++digit) {
            int nibble = year % 10;
            bcd |= nibble << (digit * 4);
            year /= 10;
        }
        return new byte[] { (byte)((bcd >> 8) & 0xff), (byte)(bcd & 0xff) };
    }

Beachten Sie, dass Sie für ein Big-Endian-Ergebnis gefragt, das etwas ungewöhnlich ist.

Andere Tipps

Hier ist eine schreckliche Brute-Force-Version. Ich bin sicher, dass es ein besserer Weg, als diese, aber es sollte auf jeden Fall arbeiten.

int digitOne = year / 1000;
int digitTwo = (year - digitOne * 1000) / 100;
int digitThree = (year - digitOne * 1000 - digitTwo * 100) / 10;
int digitFour = year - digitOne * 1000 - digitTwo * 100 - digitThree * 10;

byte[] bcdYear = new byte[] { digitOne << 4 | digitTwo, digitThree << 4 | digitFour };

Das Traurige daran ist, dass schnelle binäre zu BCD Konvertierungen in die x86-Mikroprozessor-Architektur gebaut, wenn man sie bekommen konnte!

Hier ist eine etwas sauberere Version dann Jeffreys

static byte[] IntToBCD(int input)
{
    if (input > 9999 || input < 0)
        throw new ArgumentOutOfRangeException("input");

    int thousands = input / 1000;
    int hundreds = (input -= thousands * 1000) / 100;
    int tens = (input -= hundreds * 100) / 10;
    int ones = (input -= tens * 10);

    byte[] bcd = new byte[] {
        (byte)(thousands << 4 | hundreds),
        (byte)(tens << 4 | ones)
    };

    return bcd;
}

Weitere gemeinsame Lösung

    private IEnumerable<Byte> GetBytes(Decimal value)
    {
        Byte currentByte = 0;
        Boolean odd = true;
        while (value > 0)
        {
            if (odd)
                currentByte = 0;

            Decimal rest = value % 10;
            value = (value-rest)/10;

            currentByte |= (Byte)(odd ? (Byte)rest : (Byte)((Byte)rest << 4));

            if(!odd)
                yield return currentByte;

            odd = !odd;
        }
        if(!odd)
            yield return currentByte;
    }

Ich habe eine generische Routine geschrieben unter IntToByteArray , dass Sie wie verwenden:

var yearInBytes = ConvertBigIntToBcd (2010, 2);

static byte[] IntToBCD(int input) { 
    byte[] bcd = new byte[] { 
        (byte)(input>> 8), 
        (byte)(input& 0x00FF) 
    };
    return bcd;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top