Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an Int to a BCD byte array [duplicate]

I want to convert an int to a byte[2] array using BCD.

The int in question will come from DateTime representing the Year and must be converted to two bytes.

Is there any pre-made function that does this or can you give me a simple way of doing this?

example:

int year = 2010

would output:

byte[2]{0x20, 0x10};
like image 558
Roast Avatar asked Nov 26 '22 10:11

Roast


1 Answers

    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) };
    }

Beware that you asked for a big-endian result, that's a bit unusual.

like image 76
Hans Passant Avatar answered Jan 28 '23 20:01

Hans Passant