1 2 3 4 |
typedef struct tagbigint{ u4 len; u4* dats; }bigint; |
1 2 3 4 5 6 7 |
u4 bigint_create(u4 len, bigint *xi) { xi->len=len; xi->dats=(u4*) malloc (len* sizeof (u4)); if (xi->dats==NULL) return 0; return len; } |
1 2 3 4 5 |
void bigint_release(bigint *xi) { xi->len=0; SAFE_DELETE(xi->dats); } |
1 2 3 4 5 6 7 |
u4 bigint_resize(u4 newsize, bigint *xi) { xi->len=newsize; xi->dats=(u4*) realloc (xi->dats,newsize* sizeof (u4)); if (xi->dats==NULL) return 0; return newsize; } |
1 2 3 4 5 |
void bigint_setu4(bigint *dest, u4 src) { dest->dats[0]=src; memset (&dest->dats[1], 0, (dest->len-1)* sizeof (u4)); } |
1 2 3 4 5 |
void bigint_set(bigint *dest, const bigint *src) { memcpy (dest->dats,src->dats, ((dest->len<src->len)?dest->len:src->len)* sizeof (u4)); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
inline u4 add_a(u4 len,u4*dest,u4*src) { u4 carry=0; for (u4 i=0;i<len;++i) { dest[i]+=src[i]; if (carry) { if (dest[i]>=src[i])carry=0; if (dest[i]==0xFFFFFFFF)carry=1; ++dest[i]; } else { if (dest[i]<src[i])carry=1; } } return carry; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
inline u4 add_u4(u4 len,u4*dest,u4 src) { u4 carry=0; dest[0]+=src; if (dest[0]<src)carry=1; for (u4 i=1;i<len;++i) { if (carry) { if (dest[i]!=0xFFFFFFFF)carry=0; ++dest[i]; } else { break ; } } return carry; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void bigint_add(bigint *dest, const bigint *src) { if (dest->len<src->len) { add_a(dest->len, dest->dats, src->dats); } else { if (add_a(src->len, dest->dats, src->dats)) { add_u4(dest->len-src->len, &dest->dats[src->len], 1); } } } |
1 2 3 4 5 |
void bigint_addu4(bigint *dest, u4 src,u4 pos) { if (dest->len<=pos) return ; add_u4(dest->len-pos,&dest->dats[pos],src); } |
1 2 3 4 5 6 7 8 9 |
int main() { bigint a,b; bigint_create(2, &a); bigint_create(2, &b); bigint_setu4(&a, 1234567890); bigint_setu4(&b, 3692581470); bigint_add(&a, &b); } |
BigInteger를 구현해보자 - 7. 나누기 (2) | 2009.04.25 |
---|---|
BigInteger를 구현해보자 - 6. 크기비교 (4) | 2009.04.21 |
BigInteger를 구현해보자 - 5. 시프트 연산 (0) | 2009.04.12 |
BigInteger를 구현해보자 - 4. 곱셈과 부호 체크 (0) | 2009.03.29 |
BigInteger를 구현해보자 - 3. 음수의 표현, 뺄셈 (4) | 2009.03.29 |
BigInteger를 구현해보자 - 1. BigInteger의 개요 (2) | 2009.03.29 |
댓글 영역