Convert Int to BCD Byte Array

I want to convert int to byte array [4] using BCD.

The specified object comes from the device identifier and must be talked to with the device through the serial port.

Is there any pre-made function that does this, or can you give me an easy way to do this?

Example:

int id= 29068082

outputs:

byte[4]{0x82, 0x80, 0x06, 0x29};
+5
source share
3 answers

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 will not match four bytes. More formally, if the value is less than 0 or equal to 10 ^ (n * 2) or more, where n is the number of bytes, the value will not correspond to n bytes.
  • :
    • , -10 . ( [] .)
    • 10.
    • 16 10 . ( .)
    • 10.

( , 0 , .NET, , , 0. , . , , /, , , , .)

+7

,

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

, Peter 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

Here you need to know that just using pValue / = 10 will round the value, so if, for example, the argument is "16", the first part of the byte will be correct, but the division result will be 2 (as 1.6 will be rounded). Therefore, I use the Math.Floor method.

+1
source

All Articles