在秋招中,很多求職者都遇到過(guò)關(guān)于找1的手撕代碼題,其中平頭哥面試就會(huì)讓面試者手撕這種類型的題,其中出題套路大多為從最高位/最低位開始找到1個(gè)8bit/16bit數(shù)的第一個(gè)位置,統(tǒng)計(jì)8bit/16bit數(shù)中1的個(gè)數(shù)。
大家不妨先想想自己遇到這個(gè)問(wèn)題會(huì)怎么寫這個(gè)代碼?下面小編給出幾種思路:
1、從最高位開始找出一個(gè)8bit數(shù)的第一個(gè)1的位置(二分法)(1)設(shè)計(jì)代碼
module find_first1_h2L(
input [7:0]x,
output wire [2:0]y
);
wire [3:0]data_4;
wire [1:0]data_2;
assign y[2]=|x[7:4];
assign data_4=y[2]?x[7:4]:x[3:0];
assign y[1]=|data_4[3:2];
assign data_2=y[1]?data_4[3:2]:data_4[1:0];
assign y[0]=data_2[1];
endmodule
(2)仿真代碼
module find_first1_h2L_tst();
reg [7:0]x;
wire [2:0]y;
find_first1_h2L U_find_first1_h2L(
.x(x),
.y(y)
);
initial begin
x=8'b00101110;
#20 x=8'b01100000;
#20 x=8'b00000000;
#20 x=8'b00000001;
end
endmodule
2、輸入[15:0]data_in中,從低位開始找到第一個(gè)1出現(xiàn)的位置。
(1)設(shè)計(jì)代碼
module find_one(
input clk,
input rst_n,
input [15:0]data_in,
input data_in_valid,
output reg[3:0]position
);
wire [15:0]data_in_r;
assign data_in_r=~(data_in-1)&data_in;
always@(posedge clk)
if(!rst_n)
position<=0;
else begin
case(data_in_r)
16'b0000000000000001:position<=4'd0;
16'b0000000000000010:position<=4'd1;
16'b0000000000000100:position<=4'd2;
16'b0000000000001000:position<=4'd3;
16'b0000000000010000:position<=4'd4;
16'b0000000000100000:position<=4'd5;
16'b0000000001000000:position<=4'd6;
16'b0000000010000000:position<=4'd7;
16'b0000000100000000:position<=4'd8;
16'b0000001000000000:position<=4'd9;
16'b0000010000000000:position<=4'd10;
16'b0000100000000000:position<=4'd11;
16'b0001000000000000:position<=4'd12;
16'b0010000000000000:position<=4'd13;
16'b0100000000000000:position<=4'd14;
16'b1000000000000000:position<=4'd15;
default:position<=0;
endcase
end
endmodule
(2)仿真代碼
module find_one_tst();
reg clk ;
reg rst_n ;
reg [15:0]data_in ;
reg data_in_valid;
wire[3:0] position;
find_one U_find_one(
.clk (clk ),
.rst_n (rst_n ),
.data_in (data_in ),
.data_in_valid(data_in_valid),
.position (position)
);
initial begin
clk=1;
rst_n=0;
data_in=0;
data_in_valid=0;
#20 rst_n=1;
data_in=16'd12;
data_in_valid=1;
#40 data_in=16'd9;
#20 data_in_valid=0;
end
always #10 clk=~clk;
endmodule
大家也可以用二分法試試!
3、統(tǒng)計(jì)輸入[7:0]data_in中1的個(gè)數(shù),要求優(yōu)化資源使用
(1)設(shè)計(jì)代碼
module find_number1(
input [7:0]data,
output [7:0]number
);
parameter m1 = 8'b01010101;
parameter m2 = 8'b00110011;
parameter m3 = 8'b00001111;
wire [7:0]data1;
wire [7:0]data2;
assign data1 = (data & m1) + ({data[0],data[7:1]} & m1);
assign data2 = (data1 & m2) + ({data1[1:0],data1[7:2]} & m2);
assign number = (data2 & m3) + ({data2[3:0],data2[7:4]} & m3);
endmodule
(2)仿真代碼
module tst_find_number1();
reg [7:0]data;
wire [7:0]number;
find_number1 u1(
.data (data),
.number (number)
);
initial begin
data = 8'b11010100;
end
endmodule
上面的解法并非最優(yōu),僅給大家提供一種思路。如果大家有更好的寫法,歡迎與小編交流。大家對(duì)文章中的內(nèi)容如果有疑問(wèn),歡迎留言,我們看到了會(huì)給大家解答的。也歡迎大家加入下面的qq群或者添加IC媛加入微信群進(jìn)行討論交流!