2

Possible Duplicate:
Best Algorithm for Bit Reversal ( from MSB->LSB to LSB->MSB) in C

I have a 64-bit word and I want to do the following operations on it.

First I want to do a bit-swap (swap Bit 63 with Bit 0 swap Bit 62 with Bit 1 and so on)

Once the above operation is completed I want to do a byte-swap Swap between Byte 0 and Byte 7 Byte 1 and Byte 6 and so on.

Now we do have an inbuilt function in gcc linux to do the second part bswap_64().Is there any function do do the first part available in gcc linux C

6
  • Why do you want to swap bits? either FFT or homework, IMHO. Commented Nov 8, 2011 at 23:01
  • @wildplasser.it is neither FFT not homework.I have captured some idle 10GE frames which I am trying to convert to XGMII coded frames. :) Commented Nov 8, 2011 at 23:06
  • "Dupe" is a good answer, but it's not actually a duplicate of his question. Commented Nov 8, 2011 at 23:08
  • @therefromhere: this answer addresses perfectly the question. Commented Nov 8, 2011 at 23:12
  • @AlexandreC. I disagree. It's highly relevant, but it's not actually answering the question that was asked - "Is there a standard C function for bitswapping" (of course the answer should be No, with a link to that answer). Commented Nov 8, 2011 at 23:40

1 Answer 1

7

The net effect is the same as bit-swapping each byte in place. For example, byte 0 is first copied to byte 7 with its bits reversed, then copied back to byte0 with no bit-reversal.

There's no built-in support for any of these operations, but bit-swapping each byte in place should be fairly straightforward. The most efficient method is probably a 256-element lookup table.

uint64_t the_word = /* whatever */ unsigned char *bytes = &the_word; for (i = 0; i < 7; i ++) { bytes[i] = reverse[bytes[i]]; } 

where:

const unsigned char reverse[UCHAR_MAX+1] { 0x00, 0x80, ..., 0xFF } 

You can write a small program that computes the bit-swapped value for each byte value and generates the source code for the initialization of bytes. (Or, since you're writing the code to do the computation anyway, you can just use it in your program in place of the lookup table; it depends on how important speed is.)

This assumes, for example, that CHAR_BIT == 8, which is not guaranteed by the language.

I have not tested this.

Sign up to request clarification or add additional context in comments.

2 Comments

According to benchmarks there, it might be better to manually unroll the loop and use integer arithmetic, since compilers may not be that clever (and byte addressing is usually slow). Declaring bytes as restrict could also help. Benchmarking is of course your guide here.
@AlexandreC.: I just fixed the typo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.