将int转换为BCD字节数组

我想使用BCD将int转换为byte [2]数组。

有问题的int将来自表示Year的DateTime,必须转换为两个字节。

是否有任何预制function可以做到这一点,或者你能给我一个简单的方法吗?

例:

int year = 2010 

输出:

 byte[2]{0x20, 0x10}; 

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

请注意,您要求获得大端结果,这有点不寻常。

这是一个可怕的暴力版本。 我确信有比这更好的方法,但无论如何它都应该有效。

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

令人遗憾的是,如果您能够获得它们,那么快速二进制到BCD转换就会内置到x86微处理器架构中!

这是一个比杰弗里更清洁的版本

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

更常见的解决方案

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

我在IntToByteArray发布了一个通用例程,您可以使用:

var yearInBytes = ConvertBigIntToBcd(2010,2);

 static byte[] IntToBCD(int input) { byte[] bcd = new byte[] { (byte)(input>> 8), (byte)(input& 0x00FF) }; return bcd; }