- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
It depends on what you're doing. For example when you are converting an int to a float (when your hardware can't do that), you have to know the exact integer-part-of-log2 of the input. You're going to drop the highest bit (it isn't stored in the floating point fomat, as it's always 1). If that bit wasn't 1, you're suddenly handling a different number....
Example: 1280 = 101 0000 0000b Highest 1-bit is 10, so you store exponent 10 (usually offset by 127 or something), and dropping the topmost 1-bit 01 0000 0000 (with extra zeroes tagged on at the end. This is correct.
example: 2047 = 111 1111 1111 Highest 1-bit is 10, but suppose you overestimate this and say 11. Store exponent 11, and mantissa 111 1111 1111 and you end up with 4097 when you retrieve the resulting float.....
Admin
Admin
You need at least one bit to represent zero.
Admin
Horribly unsafe version without bitshifting or division:
unsigned int countbits(unsigned int x) {
unsigned int nbits = 1; unsigned int tester = 1;
while(tester < x) { tester += tester; nbits++; }
:-)
Admin
nbits = ceiling(sqrt(abs(range)))+1
Admin
If nbits is signed, if not remove the "+1".
Admin
nbits = ceiling(sqrt(abs(range)))+1
Sooo, if range is 10,000 ..... we need 101 bits?
Admin
Admin
Admin
The correct solution is to have this function in portable C as you suggest, and on x86 instead link in a whopping 4-instruction, 9-byte assembler replacement:
The prototype in C goes like this:
For those insisting on it, it's possible to inline it as well (compile with -O2, this is gcc specific). Just put it into bits.h:
This code will be placed in-line with other code, with no function call overhead, whenever the compiler is brave enough (hence -O2).
The comments made me mostly ROTFL. You people overcomplicate so much. I bet the code runs on 32 bit x86, and there's nothing more to it than 2-5 lines of assembly. Even the binary search is simple (exercise left for the reader).
Admin
What if range==MAX_INT ? Then you roll over...
Admin
The only time range is gonna be < 0 is if max < min, which totally defeats the point of "max" and "min".
Admin
Hm ... there's more to it - and the wtf starts in the articles' text.
to represent 2022 in binary you dont need 2048 you need 2047 which is binary 11 1111 1111 (1024+512+256+128+64+32+16+8+4+2+1) 2048 is 100 0000 0000 and therefore 1 bit more than needed