Converting a int to a BCD byte array

后端 未结 6 1781
感动是毒
感动是毒 2020-12-21 01:24

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.

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-21 01:47

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

提交回复
热议问题