c - 将字节的位写入 bin 文件

标签 c

所以我试图将结构写入二进制文件。在我只写一个字节的一部分之前,它工作得很好。对于data_offset、reserved、ctl_bit,我只想将最后4、6、6位写入二进制文件。我不确定我哪里出错了。

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
};

当我写我的文件时,我试图混合使用位运算符。

    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);

最佳答案

你说:

I only want to write the last 4, 6, 6 bits to the binary file.

你的代码会:

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

(*temp).data_offset << 4;进行 4 位位移。您需要的是将除最后 4 位以外的所有位清零。您可以使用:

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

同样,你需要使用:

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

这会将除最后 6 位之外的所有位清零。

您最好创建临时变量来存储转换后的值并保存转换后的值。否则,您正在修改您的对象而无法返回到原始状态。

关于c - 将字节的位写入 bin 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29546706/

相关文章:

c - C 中的指针和数组,需要更多理解

c - 显示文件指针位置

c - *** 检测到 glibc *** free() : invalid next size (fast) -- should work?

C- fprintf 两个变量在同一行

c - 一元运算符歧义

c++ - 最优矩阵搜索(2D)问题的时间复杂度分析

C: 将(文本)文件读入数组,看不出有什么问题?

c - 从 appsink 解析数据时出现内部数据流错误

c - 在 O(logn) 中找到第 n 个 fib 数

c - 可能是多线程环境下的 Errno 描述