假设我想创建一个特定长度的二进制文件,使用前4位定义类型(应该允许16种不同类型),最后60位定义内容。
如何在C语言中构建这个?我很难找到用C语言做这件事的任何例子(这很好地解释了这一点)(我以前没有用C语言做过这种低级的工作,我想把脚弄湿…)
我只需要创建一个char[8]并手动设置每个位

/** Set bit in any sized bit block.
 *
 * @return   none
 *
 * @param   bit    - Bit number.
 * @param   bitmap - Pointer to bitmap.
 *
 * @note    Please note that this function does not know the size of the
 *          bitmap and it cannot range check the specified bit number.
 */
void SetBit(int bit, unsigned char *bitmap)
{
    int n, x;

    x = bit / 8;                        // Index to byte.
    n = bit % 8;                        // Specific bit in byte.

    bitmap[x] |= (1 << n);      // Set bit.
}

以上代码来自storing a bit in a bit of character array in C linux

最佳答案

我会创建一个特定于任务的函数,并使用一个掩码。

void setType(uint8_t type, uint8_t* header)
{
    header[0] = (header[0] & 0x0f) | (type << 4);
}

// To use:

uint8_t header[8];
setType(3, header);

我将创建一个类似的函数来设置头的每个字段。
以上假设“前四位”是指报头第一个字节的最高有效位,而不是报头第一个字节的最低有效位。

关于c - 将特定位写入二进制 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53205846/

10-11 22:05
查看更多