简体   繁体   English

如何为数组单元中的反向位顺序创建宏

[英]How to create macro for reverse bit order in array cells

I'm trying to create macro in c which purpose is re-write in reverse order the bits of each cell in array, for example, if cell A[1] is: 1100, the final cell A[1] will be: 0011.我正在尝试在 c 中创建宏,其目的是以相反的顺序重写数组中每个单元格的位,例如,如果单元格 A[1] 是:1100,则最终的单元格 A[1] 将是:0011 .

I have created the macro but I have compilation issue.我已经创建了宏,但我有编译问题。 Please let me know were I got wrong (I'm sure it can be look more compact but I wont to know what I'm missing).请让我知道我错了(我确定它看起来更紧凑,但我不知道我错过了什么)。

#include <stdio.h>


#define REVERSE(array, type) \
(   \
    type * p; \
    unsigned (type)=mask1, mask2, test;\
    mask1=1;\
    mask2=mask1<<(sizeof(type)-1);\
    for(p=(array);p ;p=p+1){\
        while((mask1=<<1)<(mask2=>>1)){\
            if(((*p)&mask1)!=((*p)&mask2)){\
                if((*p)&mask1==0){\
                    *p=*p|mask1;\
                    *p=*p^mask2;\
                }else{\
                    *p=*p^mask1;\
                    *p=*p|mask2;\
                }\
            }\
        } \
)   
int main(){
int i;
int array[]= {1,2,3,4,5};
REVERSE((array), int);
for(i=1; i<5; i++)
    printf(" \'%d\' ", array[i]);
return(0);
}

I would suggest using a look up array for this.我建议为此使用查找数组。 If the size of the type is greater than char, then you can use the look up for the byte, then shift the bytes into their correct location.如果类型的大小大于 char,那么您可以使用查找字节,然后将字节移动到正确的位置。 Not having bit twiddling will make your code run faster.不乱动会让你的代码运行得更快。 A char(byte) array of length 256 is a trivial size.长度为 256 的 char(byte) 数组是一个很小的大小。 An answer by Robert Cartaino in-place bit-reversed shuffle on an array will show you what I mean. Robert Cartaino 在数组上的地位反转洗牌的答案将向您展示我的意思。 I think his array might be short since I would expect swapping 0xff to be 0xff.我认为他的数组可能很短,因为我希望将 0xff 交换为 0xff。 His array ends at 0x7F.他的数组以 0x7F 结束。

#define REVERSE(arr,sz,type)               \
{                                          \
    size_t i;                              \
    for(i=0; i<(sz); i++) {                \
        type v1 = (arr)[i], v2 = 0;        \
        size_t j;                          \
        for(j=0; j<8*sizeof(type); j++) {  \
            v2 = (v2 << 1) | (v1 & 1);     \
            v1 >>= 1;                      \
        }                                  \
        (arr)[i] = v2;                     \
    }                                      \
}

Note: I added a sz argument to specify length of the array.注意:我添加了一个sz参数来指定数组的长度。 In your code, the for loop for(p=(array); p ;p=p+1) would work for a C string, but not for any numeric array.在您的代码中,for 循环for(p=(array); p ;p=p+1)可用于 C 字符串,但不适用于任何数字数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM