top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: How to convert 4 bytes read from binary file to integer?

+2 votes
590 views

I tried something like this

uint32_t myint;   
char n[4]; 
size_t in;
 ...
 in = fread(n, 4, 1, fp); // value n is "\000\000\000\020"
 if (!in)
   return -2;
 myint = n; // get 4 bytes to integer 

but no luck..

posted Feb 23, 2015 by Chahat Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Chahat Sharma
in = fread(n, 4, 1, fp); // value n is "\000\000\000\020" what do you mean by this line?
Are you saying that "n" contains "\000\000\000\020" this or something else.
and aslo you can't assing an array to a integer i.e
"myint = n;"

And where is your fp i.e the file which you are going to read. and what are its contains.

Please provide the sample input and expected output.

1 Answer

+1 vote
 
Best answer

Here is my sample program(Tested) As per my understanding the question.

How to run.
1. You have to creat a test.txt file which contains like "00111" I am asuming you wanted to pass 0111 only 4 bytes.
2. Save the below code smaple.c
3 Then Compile the below cource code, and validate the result.

#include <stdio.h>
#include <string.h>

 /*
    This function will only considering that n contains only 4 char.
*/

void convert_bin2int(char *n)
{
    int i, j, no  = 0;

    for (i = 0, j = 3; i < 4; i++, j--) {
        no += (n[i] - '0') << j;
    }

    printf("The int number is  : %d\n", no);
}

int main()
{
    FILE *fp = NULL;
    char n[20];
    size_t ret;

    if ((fp = fopen("test.txt", "rw+")) == NULL) {
        printf("Unable to open the file ....\n");
        return 1;
    }

    ret = fread(n, 4, 1, fp);
    printf("After fread vaule in buffer n : %s\n", ret, n);

    convert_bin2int(n); // This function will convert the binary to integer i.e 0011 will become 3

    fclose(fp);
    return 0;
}

Output:
1. test.txt (contains 0011)
After fread vaule in buffer n : 0011
The int number is : 3
2. test.txt (contains 1011)
After fread vaule in buffer n : 1011
The int number is : 11

Thanks :)

answer Feb 24, 2015 by Arshad Khan
...