0

I want to count the number of 1's in an 8-bit input and output how many ones are in it. The way I am finding this is very crude and redundant. I want to know if there is any easy and good way of finding them. My code looks like:

module my_8to4bit(in,out); input [7:0]in; output [3:0]out; assign out=(input == 1 || input == 2 || input == 4 || input == 8 || input == 16 || input == 32 || input == 64 || input == 128)?1: (input == 3 || input == 5 || input == 6 || input == 9 || input == 10 || input == 12 || input == 24 || input == 128)?2:0; 

... same goes upto all 1's in 8bit input.

Is there an easy way of finding them?

1
  • ...and it seems you made an error, too: input == 128) ? 2:0 Commented Mar 3, 2013 at 5:42

3 Answers 3

5

How about

always @* begin out = 0; for(i=0;i<8;i=i+1) begin out = out + in[i]; end end 

Should just synthesize to 8 adders, one for each bit.

Sign up to request clarification or add additional context in comments.

Comments

2

If you don't need to synthesize the code, and your simulator supports SystemVerilog syntax, you can use the $countones system function. Refer to the IEEE Std 1800-2009, for example.

Comments

0

You can look up answers in Bit Twiddling Hacks. If speed is important and space is not an issue, you might consider a 256-byte lookup table. Otherwise, probably use Brian Kernighan's way (and measure whether it is actually slower than the lookup table; it may be faster than the lookup table if memory is slow and the CPU is fast).

1 Comment

This is for HDL, not CPU programming language, so I'm not sure if most of those are appropriate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.