Hii..
Can anyone pls post the program to reverse the bits of a number.
thank you in advance...
No, but we can help you fix your code. Also, are you reversing bits or digits? Integer, float, other?
I would assume it would be for integers, as floating point numbers would get really messed up
you would want something like this
Code:int reverse(int n) { int r=0; int c; for (c=0;c<32;c++) { r=(r<<1)+(n & 1); n=n>>1; } return r; }
This code is bad for a number of reasons.
1) You assume that integers are 32 bits.
2) Hence I bet you are assuming that integers are 4 bytes and that a byte is always 8 bits. This is wrong.
3) You should use C99 styled for loops.
4) In general this is a bad implementation.
This better?
Code:#include <limits.h> /* if you're using C++ do # include <climits> */ #define INT_BITS sizeof(int) * CHAR_BITS int reverse(int input) { int hbit; int mask = 1 << (INT_BITS - 1); /* 0x80000000 for 32-bit ints */ for(unsigned int i = 0; i < INT_BITS; ++i) { hbit = input & mask; input <<= 1; input |= hbit; } return input; }
Last edited by dargueta; 03-11-2010 at 09:34 PM. Reason: Added comment
sudo rm -rf /
well next time i wont bother
Why?
sudo rm -rf /
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks