0

I explain my problem.

For example considering a 8 bit integer, to obtain symmetric number around "middle bits", bits 0 and 7 are swapped, bits 1 and 6 are swapped, bit 2 and 5 are swapped and bits 3 and 4 are swapped. (ex. 10100110 => 01100101)

The sample principal applies whatever the integer length.

Following this answer(https://stackoverflow.com/a/982139/7462275), I wrote this code that gives the expected result.

int bit_lg=8; // 8 bits (from 0 to 7)
unsigned int my_int=0b10100110, my_res=my_int;
unsigned short xbit;

for (int i=0; i<bit_lg/2;i++) {
    xbit = ((my_res >> i) ^ (my_res >> (bit_lg-1-i))) & 0b1;
    my_res = my_res ^ ((xbit << i) | (xbit << (bit_lg-1-i)));
}
printf("%B : %.8B\n",my_int,my_res);

I wonder if it possible to avoid the for loop. And obtained the result in one step ? Perhaps does it exist some __builtin_ (gcc is used) ?

Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • 1
    https://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious ? – KamilCuk Jan 12 '23 at 16:40
  • 1
    @EugeneSh.: This is a common and useful operation. It or an analog is performed frequently during signal processing on devices that are ubiquitous around the world, and the ARM architecture has an instruction for it. – Eric Postpischil Jan 12 '23 at 16:47
  • 1
    @EricPostpischil Cool, good to know (the instruction is `RBIT` for 32-bit words in ARM if anyone is interested..). I guess I'll take my comment back – Eugene Sh. Jan 12 '23 at 16:51
  • @MamilCuk. Thanks for this very good link. I consider this comment as an answer !!! – Stef1611 Jan 12 '23 at 17:10
  • @EricPostpischil. Does it exist such an instruction on Intel Core i7 proc ? – Stef1611 Jan 12 '23 at 17:20
  • 1
    @Stef1611: I do not believe so, although I stopped following the details of instruction sets when I retired a few years ago. Often, when a bit-reversal is needed in, say, an FFT, it is built into other aspects of the code, such as creating code that steps incrementally through a bit-reversed pair of indices rather than calculating the bit-reversal from scratch, or by using various table-driven algorithms. If you are looking for a practical solution, you should state what you need the bit-reversal for. – Eric Postpischil Jan 12 '23 at 17:44

0 Answers0