converting a wire value to an integer in verilog
I want to convert the data in a 开发者_运维知识库wire to an integer. For example:
wire [2:0] w = 3'b101;
I want a method that converts this to '5' and stores it in an integer. How can I do that in a better way than this:
j=1;
for(i=0; i<=2; i=i+1)
begin
a=a+(w[i]*j);
j=j*2;
end
Also, how do I convert it back to binary once I have the value in an integer? This seems a clumsy way. Thank you.
Easy! Conversion is automatic in verilog if you assign to an integer. In verilog, all the data types are just collection on bits.
integer my_int;
always @( w )
my_int = w;
As Marty said : conversion between bit vectors and integers is automatic. But there are a number of pitfalls. They are obvious if you keep in mind that an integer is a 32 bit signed value.
- Don't try to assign e.g. a 40 bit value to an integer.
- Default bit vector are unsigned so a 32 bit vector may become negative when it is an integer.
- The opposite is also true: a negative integer e.g. -3 will become an 8 vector with value 8'b11111101
I don't know why you want to convert to an integer and back. I just want to point out that arithmetic operations are fully supported on signed and unsigned bit vectors. In fact they are more powerful as there is no 32-bit limit:
reg [127:0] huge_counter;
...
always @(posedge clk)
huge_counter <= huge_counter + 128'h1;
Also using a vector as index is supported:
wire [11:0] address;
reg [ 7:0] memory [0:4095];
...
assign read_data = memory[address];
精彩评论