日期:2014-05-16 浏览次数:20742 次
#include <string.h> #include <stdio.h> #define len1 (8) #define len2 (4) int ncmp(unsigned char const *a, unsigned char const *b, int n) { int i; for (i = n - 1; i >= 0; i--) if (a[i] > b[i]) return 1; else if (a[i] < b[i]) return -1; if (i < 0) return 0; } int nsub(unsigned char *a, unsigned char *b, int n) { int i, carry = 0; for ( i = 0; i < n; i++) { a[i] -= carry; if (a[i] < b[i]) { a[i] = 0xff - b[i] + 0x01 + a[i]; carry = 1; } else a[i] -= b[i]; } return 0; } int nshr(unsigned char *a, int n) { int i; for (i = n - 1; i > 0; i--) { a[i] <<= 1; a[i] |= (a[i - 1] >> 7); } a[0] <<= 1; } int div(unsigned char a[], unsigned char b[], unsigned char c[]) { unsigned char x[len2]; int i, j; memset(x, 0, sizeof(x)); memset(c, 0, sizeof(unsigned char) * len1); for (i = 0; i < 8 * len1; i++) { nshr(x, len2); nshr(c, len1); x[0] |= (a[len1 - 1] >> 7); if (ncmp(x, b, len2) >= 0) { c[0] |= 1; nsub(x, b, len2); } nshr(a, len1); } memcpy(a, x, sizeof(x)); } int main() { unsigned char a[8], b[8], c[8]; unsigned long long *a_l = (unsigned long long *)a; unsigned long long *b_l = (unsigned long long *)b; unsigned long long *c_l = (unsigned long long *)c; *a_l = 1124141234; *b_l = 123; div(a, b, c); printf("a = %ld\n", *a_l); printf("c = %ld\n", *c_l); return 0; }
------解决方案--------------------
/* a[] 被除数 b[] 除数 c[] 商 余数放回a[]里面 */ int div(unsigned char a[], unsigned char b[], unsigned char c[])