Simple programming exercise.

Status
Not open for further replies.

g_r_o_b

Wise, Aged Ars Veteran
186
Write a function that takes an int and returns the number of bits that are on in that int.

For example countBits( 1 ) would return 1 0000...00000001
countBits( 3 ) would return 2 0000...00000010
countBits( 7 ) would return 3 0000...00000111
etc... (You get the picture)

(Make sure to calculate how many bits are used to represent an
int on your system.)

Also display the bits that are on.
Rather simple function, but may be fun for some programming newbies
to try. Saw it on a discussion of job interview questions on some
board or another.
 

DrPizza

Well-known member
93,870


I don't like your mechanism as it currently stands. And here is why:


Code:
class Dummy
{
};

template<typename N>
int numberOfSetBits(N i)
{
	int result = 0;
	for(N mask = 1; !(mask & ((N)1 << (sizeof(N)*8 - 1))); mask <<= 1)
	{
		if(mask & i)
		{
			result++;
		}
	}
	return result;
}

int main(int argc, char* argv[])
{
	Dummy n;
	cout << numberOfSetBits(n) << endl;
	return 0;
}


I don't think you should templatize it. Use a large unsigned integer and promote instead.

 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
code:<HR>
Code:
int NumBitsOn(long num)
{
  int numbits=0;
  while(num)
  {
    if (num & 1)
      ++numbits;
    num >>= 1;
  }
  return numbits;
}

Or:

code:<HR>
Code:
int NumBitsOn(long num)
{
  int numbits=0;
  int mask=1;
  while (mask < num)
  {
    if (num & mask)
      ++numbits;
    mask <<= 1;
  }
  return numbits;
}

Dunno offhand which is more efficient, not like it really matters unless sizeof(long) is several orders of magnitude larger than I'm used to.
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Use a large unsigned integer and promote instead.
Using an unsigned datatype is unnecessary. The only difference between signed/unsigned ints is the way overflow is handled.

Uncompiled and untested, but quite elegant IMHO.
Wow euzeka, great minds think alike (compare my first example, almost freaky!).

I like this line - bitsOn += (num & 1u); - good optimization, avoids a conditional branch.
 
Using an unsigned datatype is unnecessary. The only difference between signed/unsigned ints is the way overflow is handled.


I'm never sure of what signed ones do when you right shift them, if they maintain their sign or not, or otherwise act weird.




Anyway. For something generic, you want something like this. E&OE.


Code:
template<typename N>
unsigned long numberOfSetBits(const N& n)
{
	unsigned long result = 0;
	unsigned char* ch = (unsigned char*)&n;
	for(unsigned long i = 0; i < (sizeof(N) * 8); ++i)
	{
		result += ((ch[i / 8]) & (1 << (i % 8))) >> (i % 8);
	}
	return result;
}
 

Ezran

Wise, Aged Ars Veteran
137
And now for something completely different!

I just thought an alternate solution might be nice. By no means the most efficient, but certainly smaller code. If nothing else, it's just plain different. Like others, however, it disregards the idea of printing the bits.

code:
<hr>/* C Code */
unsigned int countem (unsigned int i) {
<dd>return (i & 1) + (i > 1 ? countem(i >> 1) : 0);
}

# Perl Code
sub countem {
<dd>my ($i) = @_;
<dd>return ($i & 1) + ($i > 1 ? countem($i >> 1) : 0);
}

Recursion can be fun. One line function.

-- Ezran

Edit: This only works on unsigned numbers. Could be modified for both, though.

[This message was edited by Ezran on December 06, 2001 at 02:26.]
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
I'm never sure of what signed ones do when you right shift them, if they maintain their sign or not, or otherwise act weird.
Welp, you're right. Signed numbers get sign-extended, unsigned ones get zero-extended, at least according to MSDN.

IOW, my first function would go into an infinite loop if passed a negative number.
 

YakDaGringo

Ars Tribunus Militum
1,739
I'm never sure of what signed ones do when you right shift them, if they maintain their sign or not, or otherwise act weird
It depends whether or not you're doing a logical or arithmetic shift. Logical shifts load zeros into the most signifiant bit while arithmetic shifts preserve it. Different operators; >> for logical and >>> for arithmetic, usually. The shifting operator shouldn't have anything to do with the data type, IIRC.

Factoid: Since logical and arithmetic shifts are idential when shifting left, Java doesn't even include an arithmetic shift left operator.
 

YakDaGringo

Ars Tribunus Militum
1,739
Originally posted by Richard Berg:
See above. C/C++ determines whether to do an arithmetic or logical shift depending on type.

I should know better; when I wrote a MIPS disassembler not too long ago, I implemented sllu via casting...
You already answered for C++. I was answering in general, because not all languages determine the shift based on type. As I mentioned earlier, Java is an example of this.
 
Status
Not open for further replies.