samedi 28 mars 2015

c How can i return a parity of char read from binary file




int parity (char msg[1400]) {

int parity = 0;
int i,j;
char c;

for(i=0;i<strlen(msg);i++) {
for(j=0;j<8;j++) {
c = msg[i];
int bit = (c>>j)&1;
parity ^= bit;
}
}

return parity;
}


This function return a good result, for the next example:



char* msg = malloc(sizeof(char*)*1400);
strcpy(msg,"some string");
int parity = parity(msg);


For next example the result isn't good:



char* msg = malloc(sizeof(char*)*1400);
FILE *fp;
fp = fopen(filename,"r"); //filename is a binary file
while( !feof(fp) ){
fread(msg,1399,sizeof(char),fp);
int parity = parity(msg); //--> the result isn't well
//.......
}


I saw strlen(msg) is variable at each step (192,80,200...etc) when i read from file in while. I have to change the "parity" function for second example. Any suggestions?




Aucun commentaire:

Enregistrer un commentaire