编写移位逻辑有点复杂,因为进位操作有点麻烦。它变成了看起来非常像移位和加法乘法实现的代码。
void LeftShiftN_1 (unsigned char arg[BCD_DIGITS], unsigned N) {
int i, j;
unsigned x, carry;
unsigned char accum[BCD_DIGITS];
memset(accum, '\0', sizeof(carry));
for (i=BCD_DIGITS; i>0; --i) {
x = arg[i-1];
x <<= N;
carry = 0;
for (j=i; j>=0; --j) {
carry += accum[j-1] + x % 10;
x /= 10;
accum[j-1] = carry % 10;
carry /= 10;
}
}
memcpy(arg, accum, sizeof(accum));
}
我认为从 BCD 转换并再次转换以进行转换要简单和有效得多。我以直接的方式实现,我确信转换操作可以优化。
void LeftShiftN_2 (unsigned char arg[BCD_DIGITS], unsigned N) {
int i;
unsigned accum;
accum = 0;
for (i=0; i<BCD_DIGITS; ++i) {
accum = 10*accum + arg[i];
}
accum <<= N;
for (i=BCD_DIGITS; i>0; --i) {
arg[i-1] = accum % 10;
accum /= 10;
}
}