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};
Same version as Peter O. but in VB.NET
The trick here is to be aware that simply using pValue /= 10 will round the value so if for instance the argument is "16", the first part of the byte will be correct, but the result of the division will be 2 (as 1.6 will be rounded up). Therefore I use the Math.Floor method.
Use this method.
This is essentially how it works.
(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.)
maybe a simple parse function containing this loop