c - 将位从一个字节移到一个(数组)

标签 c bit-manipulation

我解决了这个问题,但不知道如何以良好的方式发布它,所以我编辑这篇文章并将解决方案放在它的末尾。


在 C 语言中需要帮助,试图将字节位转换为相反的顺序。

我希望 Step1[] = {1,0,0,1,0,0,0,0}; 变成 {0,0,0,0,1, 0,0,1}.

void Stepper(void)
{
static uint8_t Step1[] = {1,0,0,1,0,0,0,0};
BridgeControl(Step1);
}

void BridgeControl(unsigned char *value)
{
    uint8_t tempValue;
    uint8_t bit = 8;
    uint8_t rev = 1;

    if (rev) // CW otherwise CCW
    {
        tempValue = *value;
        do{

        if(tempValue) // Right-shift one
            tempValue = 1 >> 1;
        else
            tempValue = 0 >> 1;

        }while(--bit, bit);
        *value = tempValue;
    }

我知道 bridcontrol 是完全错误的,在这里我可能需要帮助! 亲切的问候


新代码:

void BridgeControl(uint8_t *value)
{
    // For example, initial value could be 1001000 then I
    // would like the outcome to be 00001001

    uint8_t tempValue;

    uint8_t bit = 3;
    uint8_t rev = 1;

    if (rev) // CW otherwise CCW
    {
        tempValue = *value; //so... its 0b10010000
        do{
            tempValue >>=1; //1st this produce 01001000
            tempValue = 0 >> 1; //1st this produce 0010 0100
                                //2nd time produce 0001 0010
                                //3d time produce 0000 1001
        }while(--bit, bit);
    *value = tempValue;
    }
    M1BHI = value[7];
    M1BLI = value[6];
    M1AHI = value[5];
    M1ALI = value[4];
    M2BHI = value[3];
    M2BLI = value[2];
    M2AHI = value[1];
    M2ALI = value[0];
}

解决方法:

void BridgeControl(uint8_t value)
{
    uint8_t tempvalue[8];
    uint8_t i = 8;
    uint8_t cont;
    cont = value;
    do{
        value = value >> i-1;
        value = value & 1;
        tempvalue[8-i] = value;
        value = cont;
    }while(--i,i);

    M1BHI = tempvalue[7]; 
    M1BLI = tempvalue[6]; 
    M1AHI = tempvalue[5]; 
    M1ALI = tempvalue[4]; 
    M2BHI = tempvalue[3]; 
    M2BLI = tempvalue[2]; 
    M2AHI = tempvalue[1]; 
    M2ALI = tempvalue[0]; 


}

如果我想要数组中位的相反顺序,只需将 tempvalue[8-i] 更改为 tempvalue[i-1]

最佳答案

您的变量名听起来像是在尝试使用硬件。所以我猜你真的想在一个字节变量中而不是在一个 int 数组中移动位。

此语句反转字节中的位:

byte reversedVal = (byte) (val & 1 << 7
                          + val & 2 << 5
                          + val & 4 << 3
                          + val & 8 << 1
                          + val & 16 >> 1
                          + val & 32 >> 3
                          + val & 64 >> 5
                          + val & 128 >> 7);

如果你真的想反转一个 int 数组,你可以使用 scottm 建议的 LINQs Reverse 方法,但这可能不是最快的选择。

关于c - 将位从一个字节移到一个(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599195/

相关文章:

c - 即使使用 -m32,32 位 shellcode 在汇编中执行,但在 64 位操作系统上不能在 c 中执行

c - C 中指针值的更改和内存

python - 通过 SWIG : can't get void** parameters to hold their value 从 C 到 Python

python - 如何检查字节流中是否只有连续的1和0

python - int 如何作为 bool 语句求值?

c - 为什么右移 C 中的负数会在最左边的位上带来 1?

python - 对数组的连续子数组进行 XOR

c - 将排序后的未排序的连续字符串数组写入文件

sql - 函数 main() 中的编译器错误 E2451 undefined symbol 'EXEC'

C++ 对 std::bitset 的位进行操作