我想使用BCD將int轉換爲byte [4]數組。int轉換爲BCD字節數組
有問題的int將來自設備ID,他需要通過串口與設備通話。
是否有任何預製功能可以做到這一點,或者您能否給我一個簡單的方法來做到這一點?
例如:
int id= 29068082
將輸出:
byte[4]{0x82, 0x80, 0x06, 0x29};
我想使用BCD將int轉換爲byte [4]數組。int轉換爲BCD字節數組
有問題的int將來自設備ID,他需要通過串口與設備通話。
是否有任何預製功能可以做到這一點,或者您能否給我一個簡單的方法來做到這一點?
例如:
int id= 29068082
將輸出:
byte[4]{0x82, 0x80, 0x06, 0x29};
使用此方法的簡單解析函數。
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;
}
這實際上是如何工作的。
(一種優化鴻溝的價值是每一個字節預先設置爲0 - 當它分配一個新的數組時,它隱式地由.NET完成 - 並且當值達到0時停止迭代。後面的優化不是在上面的代碼中完成的,爲簡單起見,此外,如果可用,一些編譯器或彙編器提供除法/餘數例程,允許在一個除法步驟中檢索商和餘數,這是通常不需要的優化。)
也許含有該環
i=0;
while (id>0)
{
twodigits=id%100; //need 2 digits per byte
arr[i]=twodigits%10 + twodigits/10*16; //first digit on first 4 bits second digit shifted with 4 bits
id/=100;
i++;
}
版本相同彼得O.但在VB.NET
Public Shared Function ToBcd(ByVal pValue As Integer) As Byte()
If pValue < 0 OrElse pValue > 99999999 Then Throw New ArgumentOutOfRangeException("value")
Dim ret As Byte() = New Byte(3) {} 'All bytes are init with 0's
For i As Integer = 0 To 3
ret(i) = CByte(pValue Mod 10)
pValue = Math.Floor(pValue/10.0)
ret(i) = ret(i) Or CByte((pValue Mod 10) << 4)
pValue = Math.Floor(pValue/10.0)
If pValue = 0 Then Exit For
Next
Return ret
End Function
這裏的技巧是要注意,簡單地用P值/ = 10將圓值,以便如果例如說法是「16」,第一部分字節是正確的,但除法的結果將是2(因爲1.6將被舍入)。因此我使用Math.Floor方法。
我假設你的意思是',0x29}'? –
我不知道lib中的任何BCD支持,最好的選擇是使用ToString作爲中間值的自定義函數。 –
是的,它應該是0x29抱歉.. – Kingpin