-2

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.

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);
}
Julya Levin
  • 543
  • 1
  • 4
  • 11
  • 1
    Compile with `-E` (gcc) to check the expanded C code. It is in general not a good idea to have a macro create such a complex function. Note that the code might very well be badly optimized. Many modern CPUs have single instructions to bit-reverse `uint32_t` or `uint64_t`. These are likely 100 times faster than your approach. – too honest for this site Jun 29 '15 at 19:01
  • You didn't include what the error is. And why are you writing this as a macro? – Carcigenicate Jun 29 '15 at 19:01

2 Answers2

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. Not having bit twiddling will make your code run faster. A char(byte) array of length 256 is a trivial size. An answer by Robert Cartaino in-place bit-reversed shuffle on an array will show you what I mean. I think his array might be short since I would expect swapping 0xff to be 0xff. His array ends at 0x7F.

Community
  • 1
  • 1
Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30
0
#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. 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.

fferri
  • 18,285
  • 5
  • 46
  • 95