原创 N位压缩BCD加法(C51大端算法)---雁舞白沙出题

2007-3-13 19:12 4924 7 7 分类: MCU/ 嵌入式

/*------------------------------------------------------------------------
          N位压缩BCD加法(C51大端算法)---雁舞白沙出题
此题目的讨论见 http://bbs.21ic.com/club/bbs/ShowAnnounce.asp?id=2464366
HotPower@126.com    2007.3.13 于西安大雁塔菜地
------------------------------------------------------------------------*/
unsigned char databuf[24];//64位BCD加法缓冲区
unsigned char DataAdd(unsigned char *,unsigned char *,unsigned char);


void main()
{
unsigned char val;
//8位BCD加法(12 + 78 = 90)
  (unsigned char)databuf[1] = 0x12;
  (unsigned char)databuf[2] = 0x78;
  val = DataAdd(&databuf[1], &databuf[2], 1);//结果在val和databuf[1]中
//16位BCD加法(1234 + 5678 = 6912)
  (unsigned int)databuf[2] = 0x1234;
  (unsigned int)databuf[4] = 0x5678;
  val = DataAdd(&databuf[2], &databuf[4], 2);//结果在val和databuf[0]~databuf[1]中
//24位BCD加法(123456 + 456789 = 580245)
  (unsigned char)databuf[3] = 0x12;
  (unsigned int) databuf[4] = 0x3456;
  (unsigned char)databuf[6] = 0x45;
  (unsigned int) databuf[7] = 0x6789;
  val = DataAdd(&databuf[3], &databuf[6], 3);//结果在val和databuf[0]~databuf[2]中
//32位BCD加法(12345678 + 88888888 = 1 01234566)
  (unsigned long)databuf[4] = 0x12345678L;
  (unsigned long)databuf[8] = 0x88888888L;
  val = DataAdd(&databuf[4], &databuf[8], 4);//结果在val和databuf[0]~databuf[3]中
//64位BCD加法(1111111122222222 + 8888888899999999 = 1 0000000022222221)
  (unsigned long)databuf[8]  = 0x11111111L;
  (unsigned long)databuf[12] = 0x22222222L;


  (unsigned long)databuf[16] = 0x88888888L;
  (unsigned long)databuf[20] = 0x99999999L;
  val = DataAdd(&databuf[8], &databuf[16], 8);//结果在val和databuf[0]~databuf[7]中
  while(1)
  {
  }
}


unsigned char DataAdd(unsigned char *DataOneDptr,unsigned char *DataTwoDptr,unsigned char DataLend)
{
unsigned char One, Two, Tmp;//中间变量
unsigned int Sum = 0;//考虑CY位故取整型
  while(DataLend) {//不能DataLend--或--DataLend
    DataLend --;//调整到正确的数组位置
    One = DataOneDptr[DataLend];//取出正确的被加数
 Two = DataTwoDptr[DataLend];//取出正确的加数
 Sum = One + Two + Sum;//二进制求和(注意上次低位向高位的进位)
 Tmp = (One & 0xf0) + (Two & 0xf0);//为半进位做准备
 if ((Tmp != (Sum & 0xf0)) || ((Sum & 0x0f) > 9)) {//BCD码低4位调整
   Sum += 6;//凡加减10或9的都是"混球"~~~
 }
 if (Sum >= 0xa0) {//BCD码高4位调整
   Sum += 0x60;//注意"混球"~~~
 }
 databuf[DataLend] = Sum;//只存入低8位
 Sum >>= 8;//保留高8位做为下次低位向高位的进位
  }
  return Sum;//返回溢出标志(最高1位)
}

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
我要评论
0
7
关闭 站长推荐上一条 /3 下一条