我想一个int转换为字节[4]数组采用BCD。
在问题的int会从设备ID和自己的需要通过的SerialPort说话的设备。
有没有pre制功能,这是否也可以给我这样的一个简单的方法?
例如:
内部ID = 29068082
将输出:
字节[4] {为0x82,0x80的,0×06,0x29};
解决方案
使用此方法。
公共静态的byte [] ToBcd(int值){
如果(值小于0 ||值GT; 99999999)
抛出新ArgumentOutOfRangeException(价值);
byte []的RET =新的字节[4];
的for(int i = 0;我4;;我++){
RET [I] =(字节)(值10%);
值/ = 10;
保留[I] | =(字节)((值10%)所述; 4;);
值/ = 10;
}
返回RET;
}
这是本质上它是如何工作的。
如果该值小于0或大于99999999,该值将不适合在四个字节。更正式地,如果该值小于0或是10 ^(N * 2)或更大,其中n是字节数,该值将不适合在n个字节。 对于每个字节: 设置该字节到的剩余部分的值分割乘10的字节。 (这将会把当前字节的低四位[半字节]最后一个数字。) 除以10的值。 的值分割乘10的字节添加16倍的余数。 (这将会把在当前字节的高半字节的现在-最后一位数字。) 除以10的值。(一种优化是每个字节设置为0预先 - 这是隐式由.NET完成时,它分配一个新的数组 - 和停止迭代时的值达到0,这后一种优化未在$完成C $ C以上,为简单起见。另外,如果有的话,一些编译器或汇编器提供了一个除法/余例程,它允许检索一个师的步骤商和余数,优化这通常是不必要的,但。)
I want to convert an int to a byte[4] array using BCD.
The int in question will come from an device id and his needed to speak to an device via serialport.
Is there any pre-made function that does this or can you give me a simple way of doing this?
example:
int id= 29068082
would output:
byte[4]{0x82, 0x80, 0x06, 0x29};
解决方案
Use this method.
public static byte[] ToBcd(int value){
if(value<0 || value>99999999)
throw new ArgumentOutOfRangeException("value");
byte[] ret=new byte[4];
for(int i=0;i<4;i++){
ret[i]=(byte)(value%10);
value/=10;
ret[i]|=(byte)((value%10)<<4);
value/=10;
}
return ret;
}
This is essentially how it works.
If the value is less than 0 or greater than 99999999, the value won't fit in four bytes. More formally, if the value is less than 0 or is 10^(n*2) or greater, where n is the number of bytes, the value won't fit in n bytes. For each byte: Set that byte to the remainder of the value-divided-by-10 to the byte. (This will place the last digit in the low nibble [half-byte] of the current byte.) Divide the value by 10. Add 16 times the remainder of the value-divided-by-10 to the byte. (This will place the now-last digit in the high nibble of the current byte.) Divide the value by 10.(One optimization is to set every byte to 0 beforehand -- which is implicitly done by .NET when it allocates a new array -- and to stop iterating when the value reaches 0. This latter optimization is not done in the code above, for simplicity. Also, if available, some compilers or assemblers offer a divide/remainder routine that allows retrieving the quotient and remainder in one division step, an optimization which is not usually necessary though.)