c - Writing bits of a byte to bin file -


so attempting write stucture binary file. works until come writing part of byte. data_offset, reserved, , ctl_bit, want write last 4, 6, 6 bits binary file. i'm not sure going wrong.

struct tcp_head {     unsigned short  source_port;    //16 bits     unsigned short  dest_port;      //16 bits     unsigned int    seq_num;        //32 bits     unsigned int    ack_num;        //32 bits     unsigned char   data_offset;    //4 bits     unsigned short  reserved;       //6 bits     unsigned short  ctl_bit;        //6 bits     unsigned short  window;         //16 bits     unsigned short  checksum;       //16 bits     unsigned short  urgent_point;   //16 bits }; 

when write file have attempted use bit-wise operators mixed use.

    file *fileptr = fopen(filename, "wb");     int i;      if (!fileptr)     {         printf("\nerror while writing file\n");         exit(1);     }      (*temp).data_offset = (*temp).data_offset << 4;     (*temp).reserved = (*temp).reserved  << 10;     (*temp).ctl_bit = (*temp).ctl_bit  << 10;       fwrite(&(temp->dest_port), sizeof((*temp).dest_port), 1, fileptr);     fwrite(&(temp->source_port), sizeof((*temp).source_port), 1, fileptr);     fwrite(&(temp->seq_num), sizeof((*temp).seq_num), 1, fileptr);     fwrite(&(temp->ack_num), sizeof((*temp).ack_num), 1, fileptr);     fwrite(&(temp->data_offset), sizeof((*temp).data_offset), 1, fileptr);     fwrite(&(temp->reserved),sizeof((*temp).reserved), 1, fileptr);     fwrite(&(temp->ctl_bit), sizeof((*temp).ctl_bit), 1, fileptr);     fwrite(&(temp->window), sizeof((*temp).window), 1, fileptr);     fwrite(&(temp->checksum), sizeof((*temp).checksum), 1, fileptr);     fwrite(&(temp->urgent_point), sizeof((*temp).urgent_point), 1, fileptr);        fclose(fileptr); 

you said:

i want write last 4, 6, 6 bits binary file.

and code does:

(*temp).data_offset = (*temp).data_offset << 4; (*temp).reserved = (*temp).reserved  << 10; (*temp).ctl_bit = (*temp).ctl_bit  << 10; 

(*temp).data_offset << 4; bit shift 4. need zero-out bits except last 4. can using:

(*temp).data_offset = (*temp).data_offset & 0x0f; 

similarly, need use:

(*temp).reserved = (*temp).reserved  & 0x3f; (*temp).ctl_bit = (*temp).ctl_bit & 0x3f; 

that 0 out bits except last 6.

it might better create temporary variables store transformed values , save transformed values. otherwise, modifying object without being able original state.


Popular posts from this blog