以BCD转换为二进制最有效的方法 [英] Most efficient way to convert BCD to binary
本文介绍了以BCD转换为二进制最有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下code到32位BCD值(两个半UINT提供)转换为uint二进制值。
供给可以高达0X9999,的值,以形成的0x99999999的最大值。
有没有更好的(即更快)的方式来实现这一目标?
///<总结>
///转换BCD格式(8形成位数)二PLC字成单一的二进制整数。
例如///如果下= 0x5678的和Upper为0x1234,那么回报是12345678十进制或0xbc614e。
///< /总结>
///< PARAM NAME =低>最小显著16位< /参数>
///< PARAM NAME =上方式>大多数显著16位< /参数>
///<收益方式> 32位无符号整数LT; /回报>
///<说明方式>如果提供的参数是无效的,返回零< /言论>
私有静态UINT BCD2ToBin(UINT下,UINT上)
{
UINT BINVAL = 0; 如果((低级|!上部)= 0)
{
INT移位= 0;
UINT乘数= 1;
UINT bcdVal =(上<< 16)|降低; 的for(int i = 0; I< 8;我++)
{
UINT数字=(bcdVal>>移)及0xF的; 如果(数字> 9)
{
BINVAL = 0;
打破;
}
其他
{
BINVAL + =位数*乘数;
移动+ = 4;
乘法器* = 10;
}
}
} 返回BINVAL;
}
解决方案
如果您已经空间腾出一个39322元素的数组,你总是可以只是看值了。
I have the code below to convert a 32 bit BCD value (supplied in two uint halves) to a uint binary value.
The values supplied can be up to 0x9999, to form a maximum value of 0x99999999.
Is there a better (ie. quicker) way to achieve this?
/// <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;
}
解决方案
If you've space to spare for a 39,322 element array, you could always just look the value up.
这篇关于以BCD转换为二进制最有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文