質問
私はBCDを使用して、バイト[2]配列にint型に変換します。
問題のintは年を表す日時から来ると2バイトに変換する必要があります。
これを行うか、あなたは私にこれを行うための簡単な方法を与えることができます任意の既製の機能はありますか?
の例:の
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 };
それについての悲しい部分は、あなたがそれらを得ることができれば、高速バイナリは、変換は、x86マイクロプロセッサアーキテクチャに組み込まれているBCDすることです!
ここで少しクリーナーバージョンは、ジェフリーさんです>
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<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;
}
私はあなたのように使用することができます IntToByteArrayするに掲載汎用ルーチンを作りました
VAR yearInBytes = ConvertBigIntToBcd(2010 2)
static byte[] IntToBCD(int input) {
byte[] bcd = new byte[] {
(byte)(input>> 8),
(byte)(input& 0x00FF)
};
return bcd;
}
所属していません StackOverflow