Reputation: 1
I am writing a program with GNU Bignum and what i want to do is simply read a binary file, and use the raw data as a Bignum integer, But whenever i read this file even though it is about 2MB long and try to print the number it gives me a very small number like 67 or 300, i have tried it with different files and it all behaves the same. the source code below might give you guys an idea of what i am talking about.
#include <stdlib.h>
#include <stdio.h>
#include <gmp.h>
#include <string.h>
int main()
{
mpz_t data_in;
mpz_t data_out;
FILE *in_file;
FILE * out_file;
unsigned long file_length;
void* data;
//initialize data
mpz_init(data_in);
mpz_init(data_out);
in_file = fopen("main.c","rb");
out_file = fopen("out.txt","wb");
//get file length.
fseek(in_file,0,SEEK_END);
file_length = ftell(in_file);
fseek(in_file,0,SEEK_SET);
//allocate memory.
data = malloc(file_length);
//read file into memory.
fread(data,file_length,1,in_file);
//check to see if the first byte is zero
/*if(data[1]== 0)
{
printf(" first byte zero\n");
}
else
{
printf("first byte OK\nFile length %lu\n Data read %d\n",file_length,strlen(data));
}
*/
//import data as integer.
mpz_import(data_in,1,file_length,sizeof(data[0]),0,0,data);
//output number in the screen
gmp_printf(" Data is %Zd\n",data_in);
mpz_out_str(NULL,10,data_in);
fclose(in_file);
fclose(out_file);
return 0;
}
What could be wrong here ?
Upvotes: 0
Views: 975
Reputation: 434675
I think you have the second and third arguments to mpz_import
reversed, I think you want this (with ugly comments for clarity):
mpz_import(
data_in, /* mpz_t rop */
file_length, /* size_t count */
1, /* int order */
sizeof(data[0]), /* int size */
0, /* int endian */
0, /* size_t nails */
data /* const void *op */
);
The result of reversing the second and third arguments would be mpz_import
reading less data than you want and hence your small values.
Upvotes: 1