I have a matrix (2-D int pointer int **mat) that I am trying to write to a file in Linux in Little-endian convention.
Here is my function that writes to the file:
#define BUFF_SIZE 4
void write_matrix(int **mat, int n, char *dest_file) {
    int i, j;
    char buff[BUFF_SIZE];
    int fd = open(dest_file, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IXUSR);
    if (fd < 0) {
        printf("Error: Could not open the file \"%s\".\n", dest_file);
    }
    buff[0] = (n & 0x000000ff);
    buff[1] = (n & 0x0000ff00) >> 8;
    buff[2] = (n & 0x00ff0000) >> 16;
    buff[3] = (n & 0xff000000) >> 24;
    write(fd, buff, BUFF_SIZE);
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            buff[0] = (mat[i][j] & 0x000000ff);
            buff[1] = (mat[i][j] & 0x0000ff00) >> 8;
            buff[2] = (mat[i][j] & 0x00ff0000) >> 16;
            buff[3] = (mat[i][j] & 0xff000000) >> 24;
            if (write(fd, buff, BUFF_SIZE) != BUFF_SIZE) {
                close(fd);
                printf("Error: could not write to file.\n");
                return;
            }
        }
    }
    close(fd);
}
The problem is that when I write out a matrix large enough of the form mat[i][i] = i (let's say 512 X 512), I think I get an overflow, since I get weird negative numbers.
To convert back I use:
void read_matrix(int fd, int **mat, int n, char buff[]) {
    int i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            assert(read(fd, buff, BUFF_SIZE) == BUFF_SIZE);
            mat[i][j] = byteToInt(buff);
        }
    }
}
int byteToInt(char buff[]) {
    return (buff[3] << 24) | (buff[2] << 16) | (buff[1] << 8) | (buff[0]);
}
What an I doing wrong?
EDITED:
- Added the - read_matrixfunction.
- It seems like I'm getting a - shortinstead on an- int, since 384 = (110000000) becomes -128 = (bin) 1000000
- Did a test, and found out that: - char c = 128; int i = 0; i |= c; - gives - i = -128. Why????
 
     
     
     
    