Question:
C programming. bit reverse with 16elements lookup table?
Joy
2014-10-03 17:09:06 UTC
Question1
I am trying to write a program which reverse bits with lookup table(16elements)
?? Here is my code ,but it only works for 1~800
It cannot work for a large number like 80000000
Why?

Question2
How can I replace Uchar_t * pa, * pb; with a union?

Thank you very much

#include
#include
#include
#include


typedef enum{FALSE,TRUE} Bool_t;
typedef unsigned char Uchar_t;
typedef unsigned int Uint_t;
/* main program reads in a value in hex to reverse
if the value is zero, the program stops */
Uchar_t lookup[16]={
0x0, 0x8, 0x4, 0xC,
0x2, 0xA, 0x6, 0xE,
0x1, 0x9, 0x5, 0xD,
0x3, 0xB, 0x7, 0xF };


int main(int argc, char ** argv){
Uint_t val, z;
Uchar_t * pa, * pb; /* can you replace this pointer stuff with a union? */
pa = (Uchar_t *) &val;
pb = (Uchar_t *) &z;
int i;
while(TRUE){
printf("Value to reverse in hex: ");
scanf("%x", &val);
if(!val) return FALSE; /* zero value exits */


for(i=0;i<=3;i++) *(pb+i) = lookup[*(pa+3-i)]<<4;

printf("Reverse is: %08x\n",z);
}
}
Four answers:
justme
2014-10-04 06:40:58 UTC
So you just want to reverse the bits in an integer?

Example:

a = 0x80000000

and when reversed:

a = 0x00000001



int a, b, tmp;



a = 0x80000000;

tmp = 0;



for (b = 0; b < 32; b++){

tmp <<= 1;

if (a & 0x1)

tmp |= 1;

a >>= 1;

}

a = tmp;

//print the value of a





EDIT: OK, using your lookup table:



int a, b, tmp;



a = 0x12345678;

tmp = 0;

for (b = 0; b < 8; b++){

tmp <<= 4;

tmp |= lookup[a & 0x0f];

a >>= 4;

}

a = tmp;

//print the value of a

}
Wilma
2016-04-28 09:24:04 UTC
1
mark_poc
2014-10-04 18:04:02 UTC
int main()

{

unsigned int val = 0;

unsigned int reversed = 0;

while (1)

{

printf("\n\nValue to reverse in hex: ");

scanf("%x", &val);

if (val == 0)

break;

cout << "\nReversed order = ";



for (int i = 0; i < 8; i++)

{

reversed <<= 4;

reversed += lookup[val & 15];

val >>= 4;

}

cout << hex << reversed;

}



return 0;

}



Here is another way to do it. Just mask off all of the bits in the 32 bit integer except for the last nibble. Then, just use that nibble as an index into the look up table and add that to 'reversed'. Then shift left 4 more bits to get the next nibble while shifting 'reserved' right 4, and so on. I am a C++ guy so I used cout instead of printf.
2017-01-22 09:35:11 UTC
2


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...