Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binary Reverse

Status
Not open for further replies.

xeneize

Technical User
Oct 7, 2002
1
CA
May anyone help me to resolve this problem. How do I reverse a binary number. Lets say I have 00000001 00000010 10000000 01000000 then I have to show 10000000 01000000 00000001 00000010.
Thanks
 
int reverse(int value)
{
int ii;
int tmp=value;
int result=0;

for(ii=0; ii<sizeof(int)*8-1; ii++)
{
result|=tmp&1;
tmp>>=1;
result<<=1;
}

return(result);
}
 
How bout something like

struct flipIt{
unsigned bit0: 1;
unsigned bit1: 1;
unsigned bit2: 1;
unsigned bit3: 1;
unsigned bit4: 1;
unsigned bit5: 1;
unsigned bit6: 1;
unsigned bit7: 1;

void Reverse()
{
if(bit0!=bit7)
bit0^=bit7^=bit0^=bit7;

if(bit1!=bit6)
bit1^=bit6^=bit1^=bit6;

if(bit2!=bit5)
bit2^=bit5^=bit2^=bit5;

if(bit3!=bit4)
bit3^=bit4^=bit3^=bit4;
}
};

union flipUnion{
unsigned char c;
flipIt f;
};


flipUnion f;
f.c = value;
f.f.Reverse();


Just do it 8 bits at a time.

Matt
 
I wrote this up quick... im not sure if reverse works as intended. you get the idea though.. (I HOPE)

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top