我的回答可能有点晚了,但这是我解决问题的方法:
1-首先我需要找到数字的长度,例如:3422 -> 4, 100 -> 3
public static class NumbersUtility
{
public static int FindNumberLength(int number)
{
return Convert.ToInt32( Math.Floor(Math.Log(number,10))+1);
}
public static int FindNumberDivisor(int number)
{
return Convert.ToInt32(Math.Pow(10, FindNumberLength(number)-1));
}
public static int[] FindNumberElements(int number)
{
int[] elements = new int[FindNumberLength(number)];
int divisor = FindNumberDivisor(number);
for (int i = 0; i < elements.Length; i++)
{
elements[i] = number/divisor;
number %= divisor;
divisor /= 10;
}
return elements;
}
}
之后,我将数字拆分为一个数组,这样可以更轻松地遍历和处理数字。但是有一个警告,如果数字是奇数长度,则必须将零添加到数组的开头。
public static byte[] IntToBCD(int[] input, bool isLittleEndian = false)
{
byte[] outArr = new byte[Convert.ToInt32(Math.Ceiling((double) input.Length/2))];
//Handle the case of an odd number in which a zero should be added at the beginning
if (input.Length%2 != 0)
{
//Use a temp array to expand the old one, you can use lists or
//anyother datastructure if you wish to
int[] newInput = new int[input.Length+1];
Array.Copy(input,0,newInput,1,input.Length);
newInput[0] = 0;
input = newInput;
//Dispose the temp array
newInput = null;
}
for (int i = 0; i < outArr.Length; i++)
{
outArr[i]=(byte)(input[i*2]<<4);
outArr[i]|=(byte)(input[i*2+1]);
}
return outArr;
}