Search code examples
cio

How can bytes in char array represent integers?


So let's say I have char array that I read from binary file (like ext2 formatted filesystem image file).

Now I need to read integer starting at offset byte 1024(<--that's the offset from start of data). Is there any neat way of doing it. The integer could be any number. So I believe can be represented in integer size of 4 byte on my system (x86-64).

I believe I need to use strtol like:

/* Convert the provided value to a decimal long */
char *eptr=malloc(4);// 4 bytes becuase sizeof int is 4 bytes
....
int valread=read(fd,eptr,4);//fd is to ext2 formatted image file (from file system)
result = strtol(eptr, &v, 10);

The above is long so is this the number to represent a integer 32 bit?

Should eptr be null terminated?

Is this correct or not?


Solution

  • I have char array that I read from binary file (like ext2 formatted filesystem image file).

    Open the file in binary mode

    const char *file_name = ...;
    FILE *infile = fopen(file_name, "rb");  // b is for binary
    if (infile == NULL) {
      fprintf(stderr, "Unable to open file <%s>.\n", file_name);
      exit(1);
    }
    

    I need to read integer starting at offset byte 1024 ...

    long offset = 1024; 
    if (fseek(infile, offset, SEEK_SET)) {
      fprintf(stderr, "Unable to seek to %ld.\n", offset);
      exit(1);
    } 
    

    So I believe can be represented in integer size of 4 byte on my system

    Rather than use int, which may differ from 4-bytes, consider int32_t from <stdint.h>.

    int32_t data4;
    if (fread(&data4, sizeof data4, 1, infile) != 1) {
      fprintf(stderr, "Unable to read data.\n");
      exit(1);
    } 
    

    Account for Endian.

    As file data is little-endian, convert to native endian. See #include <endian.h>.

    data4 = le32toh(data4);
    

    Clean up when done

    // Use data4
    
    fclose(infile);
    

    believe I need to use strtol like

    No. strtol() examines a string and returns a long. File data is binary and not a string.