我有下面的代碼將32位BCD值(以兩個半角提供)轉換爲uint二進制值。將BCD轉換爲二進制的最有效方法
提供的值可以高達0x9999,以形成最大值0x99999999。
有沒有更好的(即更快)的方式來實現這一目標?
/// <summary>
/// Convert two PLC words in BCD format (forming 8 digit number) into single binary integer.
/// e.g. If Lower = 0x5678 and Upper = 0x1234, then Return is 12345678 decimal, or 0xbc614e.
/// </summary>
/// <param name="lower">Least significant 16 bits.</param>
/// <param name="upper">Most significant 16 bits.</param>
/// <returns>32 bit unsigned integer.</returns>
/// <remarks>If the parameters supplied are invalid, returns zero.</remarks>
private static uint BCD2ToBin(uint lower, uint upper)
{
uint binVal = 0;
if ((lower | upper) != 0)
{
int shift = 0;
uint multiplier = 1;
uint bcdVal = (upper << 16) | lower;
for (int i = 0; i < 8; i++)
{
uint digit = (bcdVal >> shift) & 0xf;
if (digit > 9)
{
binVal = 0;
break;
}
else
{
binVal += digit * multiplier;
shift += 4;
multiplier *= 10;
}
}
}
return binVal;
}
看起來相當好給我。 – Spence 2009-01-20 20:38:00
爲什麼需要兩個提示而不是ushorts,如果每個只代表16位? – 2009-01-20 20:38:44