#### Archived

This topic is now archived and is closed to further replies.

# Binary Bits

This topic is 6065 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

This is my first post on Gamedev. I would like to know if there is away of geting the number of binary bits used to represent a decimal number using the log() and log10(). e.g you need 3 bits to represent the number 6. Is there a way of using the above functions? Please help me out!

##### Share on other sites
I'd go with writing my own bit-searching function. You start from the top, and when you hit a 1, exit:

  // 32 bits searchingint value = inputValue;if (!value) return 0;int temp = value;int count = 0;while (!(temp & 0x80000000)) { temp <<= 1; count++;}return 32 - count;

This is only a little code-snippet I wrote in a few seconds or so, so pleaz don't go on laughing for any bugs or alike. Try make optimizations yourself...

Edited by - coelurus on December 13, 2001 3:55:46 PM

Edited by - coelurus on December 13, 2001 3:56:25 PM

##### Share on other sites
/*
**
** [func] - bitcount.
** [desc] - returns the number of bits required to hold a value.
** [entr] - int value; the value.
** [exit] - int; the number of bits required to hold a value.
**
*/
int bitcount(int value) {
int cmp = 2, retval = 0;

for (int count=1; count <= 32; count++) {
if ((cmp - 1) >= value) {
retval = count;
count = 32;
}
else cmp *= 2;
}
return (retval);
}

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.

##### Share on other sites
Bits are always binary; the term "bit" comes from "binary digit."

##### Share on other sites
quote:
Original post by merlin9x9
Bits are always binary; the term "bit" comes from "binary digit."

Not when you''re doing Information and Signal Theory (bit = binary unit).

##### Share on other sites
quote:
Original post by shuks
I would like to know if there is away of geting the number of binary bits used to represent a decimal number using the log() and log10(). e.g you need 3 bits to represent the number 6. Is there a way of using the above functions?

Here''s hoping it''s not for a homework assignment...

But I think the answer you''re looking for is:

  int countBits( int value ){ assert( value != 0 ); return( (int)( log10( value ) / log10( 2 ) ) + 1 );}

(and here''s hoping my math skills are still what they were)

Cheers,
-scott

##### Share on other sites
Thanks guys!
The code snippets really helped. I knew how to obtain the number of bits.

I would like to thank scott for his solution. It was what i wanted.
By the way, your math skills are excellent.
Thanks everyone.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631781
• Total Posts
3002314
×