#include <stdio.h>
//#define SHOW
#pragma warning(disable:4996)
void binout(char *s, char v)
{
char i;
printf("%s", s);
for (i = 0; i < 8; i++)
{
if (v & 0x80)
putchar('1');
else
putchar('0');
if (i == 0)
putchar('.');
v <<= 1;
}
}
short multiply(char x, char y)
{
// 所有寄存器全部采用算术移位
// 且都采用双符号位
char a = 0;
char b2 = ~x + 1;
char c = y;
char cn = 0;
char i;
for (i = 1; i <= 8; i++) // 7位数值位需要8步操作
{
if ((c & 1) == 0 && cn == 1)
a += x;
else if ((c & 1) == 1 && cn == 0)
a += b2;
if (i != 8)
{
cn = c & 1; // c的最低位移入cn
c >>= 1;
// a的最低位移入c的最高位
if (a & 1)
c |= 0x80;
else
c &= 0x7f;
a >>= 1;
}
#ifdef SHOW
binout("a=", a);
binout(" c=", c);
putchar('\n');
#endif
}
return (short)((a << 7) + ((c >> 1) & 0x7f));
}
void test(char a, char b)
{
printf("%d * %d = %d\n", a, b, multiply(a, b));
}
void check(void)
{
char a, b;
short c;
int cnt = 0;
FILE *fp = fopen("result.txt", "w");
if (fp == NULL)
return;
for (a = -64; a <= 63; a++)
{
for (b = -64; b <= 63; b++)
{
c = multiply((char)a, (char)b);
if (a * b != c)
{
fprintf(fp, "Warning: %d * %d != %d\n", a, b, c);
cnt++;
}
else
fprintf(fp, "%d * %d = %d\n", a, b, c);
}
}
fclose(fp);
printf("Warning count: %d\n", cnt);
}
int main(void)
{
check();
test(-5, -3);
test(-9, -16);
test(-32, 1);
test(-13, -11);
return 0;
}