1の数を数える

入出力

名前 入力・出力 ビット幅 説明
din 入力 N
dout 入力 log N + 1 1の数

動作例

入力 出力
din dout
00000000 0
00001000 1
01001000 2
01011000 3
10000010 2
01111000 4
10101010 4
11111111 8

コード

  • VerilogHDL
count_ones.v
module count_ones(din, dout);
  parameter N = 8;
  parameter LOG_N = 3;
 
  input [N-1:0] din;
  output [LOG_N:0] dout;
 
  reg [LOG_N:0] sum;
 
 
  integer i;
  always@(din)
  begin
    sum = 0;
    for(i=0;i<N;i=i+1)
      sum = sum + din[i];
  end
 
  assign dout = sum;
endmodule
  • VHDL
multiplexer.vhd
library	IEEE;
use IEEE.std_logic_1164.all;
 
entity count_ones is
  generic( N : integer := 8;
           LOG_N := integer 3 );
  port (din : in std_logic_vecort(N-1 downto 0);
        dout : out std_logic_vector(LOG_N downto 0) );
end count_ones;
 
architecture count_ones_body of count_ones is
  signal sum : integer := 0;
begin
  for i in 0 to N-1 loop
    if(din(i) = '1') then
     sum := sum + 1;
    end if;
  end loop;
end count_ones_body;

シミュレーション

  • テストベンチ(VerilogHDL)
count_ones_tb.v
`timescale 1ns / 1ps
module count_ones_tb;
  parameter N=8;
  parameter M=3+1;
 
  reg [N-1:0] din;
  wire [M-1:0] dout;
 
  count_ones count_ones_d(.din(din), .dout(dout));
 
  initial begin
    din = 0;
    #100 din = 8'b00000000;
    #100 din = 8'b01000000;
    #100 din = 8'b00100100;
    #100 din = 8'b01100100;
    #100 din = 8'b10001001;
    #100 din = 8'b01010101;
    #100 din = 8'b10101010;
    #100 din = 8'b11111111;
    #100 din = 8'b00000000;
  end
 
endmodule
  • テストベンチ(VHDL)
  • シミュレーション波形

関連項目