wu :: forums (http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi)
riddles >> cs >> REVERSE  bits in 8 byte
(Message started by: puzzlecracker on Dec 17th, 2004, 11:33pm)

Title: REVERSE  bits in 8 byte
Post by puzzlecracker on Dec 17th, 2004, 11:33pm
Using C, but without loops or lookup tables, write a routine which reverses  the bits in an 8-bit byte




Title: Re: REVERSE  bits in 8 byte
Post by John_Gaughan on Dec 18th, 2004, 10:48am
This should do the trick. Can anyone make it shorter?
::
[hide]unsigned char reverse (unsigned char n)
{
 return ((n & 0x01) << 7)
 | ((n & 0x02) << 5)
 | ((n & 0x04) << 3)
 | ((n & 0x08) << 1)
 | ((n & 0x10) >> 1)
 | ((n & 0x20) >> 3)
 | ((n & 0x40) >> 5)
 | ((n & 0x80) >> 7);
}
[/hide]::

Title: Re: REVERSE  bits in 8 byte
Post by towr on Dec 18th, 2004, 2:07pm
something like
::[hide]
n = n&11110000 >>4 | n&00001111 << 4;
n = n&11001100 >>2 | n&00110011 << 2;
return  n&10101010 >>1 | n&01010101 << 1;

I didn't actually bothered to check whether this does what I think it ought to do, but if it doesn't it should give you the idea of what does..
[/hide]::

Title: Re: REVERSE  bits in 8 byte
Post by puzzlecracker on Dec 19th, 2004, 1:39pm
can both of you, or anyone else pretty much, explain that... thx


I thought to actually flipping the bits as[hide]
n=n^255, but only flips them.... [/hide]

I was wrong... please explain the logic.. thx


Title: Re: REVERSE  bits in 8 byte
Post by puzzlecracker on Dec 19th, 2004, 3:23pm
never mind (i am an idiot) -- towr - you're a genous of modern creation!



Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board