c - 从 8 位数据中去除 C 中的奇偶校验位,后跟 1 个奇偶校验位

标签 c parity

我有一个位缓冲区,其中包含 8 位数据,后跟 1 个奇偶校验位。这种模式不断重复。缓冲区当前存储为八位字节数组。

示例(p 是奇偶校验位):

0001 0001 p000 0100 0p00 0001 00p01 1100 ...

应该变成

0001 0001 0000 1000 0000 0100 0111 00 ...

基本上,我需要去除每九个位来获取数据位。我怎样才能做到这一点?

这与 another question 有关有时间在这里问。

这是在 32 位机器上,因此相关问题的解决方案可能不适用。最大可能的位数是 45,即 5 个数据八位字节

到目前为止,这是我尝试过的。我创建了一个“ bool ”数组,并根据八位位组的位集将位添加到数组中。然后我查看数组的每九个索引并通过它离开。然后将剩余的数组向下移动一个索引。然后我只剩下数据位了。我在想可能有更好的方法来做到这一点。

最佳答案

您拥有一个位数组的想法很好。只需通过 32 位数字(缓冲区)实现位数组。

从缓冲区中间移除一点:

void remove_bit(uint32_t* buffer, int* occupancy, int pos)
{
    assert(*occupancy > 0);
    uint32_t high_half = *buffer >> pos >> 1;
    uint32_t low_half = *buffer << (32 - pos) >> (32 - pos);
    *buffer = high_half | low_half;
    --*occupancy;
}

向缓冲区添加一个字节:

void add_byte(uint32_t* buffer, int* occupancy, uint8_t byte)
{
    assert(*occupancy <= 24);
    *buffer = (*buffer << 8) | byte;
    *occupancy += 8;
}

从缓冲区中删除一个字节:

uint8_t remove_byte(uint32_t* buffer, int* occupancy)
{
    uint8_t result = *buffer >> (*occupancy - 8);
    assert(*occupancy >= 8);
    *occupancy -= 8;
    return result;
}

您必须安排调用以使缓冲区永远不会溢出。例如:

buffer = 0;
occupancy = 0;
add_byte(buffer, occupancy, *input++);
add_byte(buffer, occupancy, *input++);
remove_bit(buffer, occupancy, 7);
*output++ = remove_byte(buffer, occupancy);
add_byte(buffer, occupancy, *input++);
remove_bit(buffer, occupancy, 6);
*output++ = remove_byte(buffer, occupancy);
... (there are only 6 input bytes, so this should be easy)

关于c - 从 8 位数据中去除 C 中的奇偶校验位,后跟 1 个奇偶校验位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10978215/

相关文章:

c - 解析 C 文件 I/O

c - 偏移量如何进入堆栈?

ios - 如何知道一个数字在 Swift 中是奇数还是偶数?

c - 奇偶查找表生成

blockchain - 我如何以某种方式运行 Substrate,以便立即验证交易以减少开发费用?

java - 奇偶校验 - 递归java

c - 在 C 中使用内联汇编进行位奇偶校验?

c - 是否有必要调用 pthread_exit()

c - 使用宏在 C 中创建循环

c - 了解这种基于 C 语言的冒泡排序