如何将位数组转换为char

时间:2013-04-11 16:47:07

标签: c++ visual-studio-2010 byte bit-manipulation unsigned

我试图根据一些要求修改LSB(最低有效位)来编辑缓冲区的每个字节。 我使用unsigned char类型作为字节,所以请告诉我 IF 这是正确/错误的。

unsigned char buffer[MAXBUFFER];

接下来,我正在使用此功能

char *uchartob(char s[9], unsigned char u)

修改并返回第一个参数作为位数组。这个函数工作正常,因为数组中的位代表第二个参数。

这是麻烦开始的地方。我要指出我正在尝试做什么一步一步所以你们可以让我知道我在哪里走错了路。

在变量

中保存上述函数的结果(调用缓冲区的每个元素)
char binary_byte[9];             // array of bits

测试LSB 只是将它与上面的某个标志进行比较。

if (binary_byte[7]==bit_flag)     // i go on and modify it like this
binary_byte[7]=0;                // or 1, depending on the case

接下来,我正在尝试转换位数 binary_byte(它是一个位数组,不是吗?)回到字节/ unsigned char 并更新缓冲区中的数据同时。我希望自己足够清楚,因为我现在很困惑。

buffer[position_in_buffer]=binary_byte[0]<<7| // actualize the current BYTE in the buffer
                        binary_byte[1]<<6|
                        binary_byte[2]<<5|
                        binary_byte[3]<<4|
                        binary_byte[4]<<3|
                        binary_byte[5]<<2|
                        binary_byte[6]<<1|
                        binary_byte[7];

请记住,位置binary_byte [7]的位可能会被修改,这就是所有这一点。

解决方案不是很优雅,但是它正在工作,即使我对我所做的事情感到非常不安全(我尝试使用按位运算符但没有成功)

奇怪的是当我尝试从缓冲区打印更新的字符时。它与前一个字符具有相同的位,但它是完全不同的。 enter image description here

我的最后一个问题是:只改变字节中的LSB有什么影响?我应该期待什么?。正如你所看到的,即使我不应该,我也只会获得“新”角色。

2 个答案:

答案 0 :(得分:2)

按位:

set bit =&gt; a |= 1 << x;

重置位=&gt; a &= ~(1 << x);

位检查=&gt; a & (1 << x);

翻转位=&gt; a ^= (1 << x)

如果您无法管理,可以随时使用std::bitset

帮助程序宏

#define SET_BIT(where, bit_number) ((where) |= 1 << (bit_number))

#define RESET_BIT(where, bit_number) ((where) &= ~(1 << (bit_number)))

#define FLIP_BIT(where, bit_number) ((where) ^= 1 << (bit_number))

#define GET_BIT_VALUE(where, bit_number) (((where) & (1 << (bit_number))) >> bit_number) //这将重新调整0或1

帮助应用程序打印位

#include <iostream>
#include <cstdint>

#define GET_BIT_VALUE(where, bit_number) (((where) & (1 << (bit_number))) >> bit_number)

template<typename T>
void print_bits(T const& value)
{
    for(uint8_t bit_count = 0;
        bit_count < (sizeof(T)<<3);
        ++bit_count)
    {
        std::cout << GET_BIT_VALUE(value, bit_count) << std::endl;
    }
}

int main()
{
    unsigned int f = 8;
    print_bits(f);
}

答案 1 :(得分:2)

所以我仍然不确定你要在这里完成什么,但是因为你试图修改一个字节的各个位,我建议使用以下数据结构:

union bit_byte
{
    struct{
        unsigned bit0 : 1;
        unsigned bit1 : 1;
        unsigned bit2 : 1;
        unsigned bit3 : 1;
        unsigned bit4 : 1;
        unsigned bit5 : 1;
        unsigned bit6 : 1;
        unsigned bit7 : 1;
    } bits;

    unsigned char all;
};

这将允许您访问字节的每个位并仍然获得字节表示。这里有一些快速示例代码:

bit_byte myValue;
myValue.bits.bit0 = 1;    // Set the LSB

// Test the LSB
if(myValue.bits.bit0 == 1) {
    myValue.bits.bit7 = 1;
}

printf("%i", myValue.all);