views:

622

answers:

3

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};
+2  A: 

Here's a terrible brute-force version. I'm sure there's a better way than this, but it ought to work anyway.

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

The sad part about it is that fast binary to BCD conversions are built into the x86 microprocessor architecture, if you could get at them!

Jeffrey L Whitledge
+1  A: 

Here is a slightly cleaner version then Jeffrey's

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;
}
Matthew Whited
You can probably come up with some crazy way that uses Boolean logic and shifting... but this will be much nicer to maintain.
Matthew Whited
+2  A: 
    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.

Hans Passant
Big-endian may not very unusual if he is working with embedded hardware.
Matthew Whited
Works great thanks!In this case i dont think Endian matters, I am careful with it but in this case it ok.
Lily