Skip to content

Instantly share code, notes, and snippets.

@polachok
Created May 19, 2012 09:09
Show Gist options
  • Save polachok/2730178 to your computer and use it in GitHub Desktop.
Save polachok/2730178 to your computer and use it in GitHub Desktop.
bigint lol
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct bigint {
unsigned char *p;
int size;
};
typedef struct bigint BigInt;
int
bi_init(BigInt *a) {
if ((a->p = malloc(sizeof(unsigned char))) == NULL)
perror("malloc");
a->size = 1;
return 0;
}
int
bi_set(BigInt *a, int n) {
int s;
s = sizeof(int)/sizeof(unsigned char);
if (s > a->size)
a->p = realloc(a->p, s);
if (!a) {
perror("realloc");
return 1;
}
memcpy(a->p, &n, s);
a->size = s;
return 0;
}
void
bi_shiftright(BigInt *a, int n) {
int i,j;
for (j = 0; j < n; j++) {
for (i = 0; i < a->size; i++) {
if (i && (a->p[i] & 1))
a->p[i-1] |= (1<<7);
a->p[i] >>= 1;
}
}
}
void
bi_hexdump(BigInt *a) {
int i;
for (i = 0; i < a->size; i++)
printf("0x%hhx\t", a->p[i]);
}
int main() {
BigInt a;
bi_init(&a);
bi_set(&a, 512);
bi_hexdump(&a);
puts("");
bi_shiftright(&a, 1);
bi_hexdump(&a);
puts("");
bi_shiftright(&a, 1);
bi_hexdump(&a);
puts("");
bi_shiftright(&a, 2);
bi_hexdump(&a);
puts("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment