由网友(卑微的等待苍老了容颜)分享简介:我想一个int转换为字节[2]数组采用BCD。在讨论的INT将来自日期时间再presenting年,并必须转换为两个字节。有没有pre制功能,这是否也可以给我这样的一个简单的方法?例如: INT年= 2010将输出:字节[2] {为0x20,0x10的};解决方案 静态的byte [] Year2Bcd(INT年){...
我想一个int转换为字节[2]数组采用BCD。
在讨论的INT将来自日期时间再presenting年,并必须转换为两个字节。
有没有pre制功能,这是否也可以给我这样的一个简单的方法?
例如:
INT年= 2010
将输出:
字节[2] {为0x20,0x10的};
解决方案
静态的byte [] Year2Bcd(INT年){
如果(年℃,||一年> 9999)抛出新的ArgumentException();
INT BCD = 0;
对(INT位= 0;位4; ++位){
INT半字节=一年10%;
BCD | =四位<< (数字* 4);
年/ = 10;
}
返回新的字节[] {(字节)((BCD>> 8)及0xFF的),(字节)(BCD&安培; 0xFF的)};
}
要注意的是,你问一个大端的结果,这是一个有点不寻常。
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};
解决方案
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.
相关推荐
最新文章