converting a wire value to an integer in verilog
Solution 1
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;
Solution 2
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];
Brahadeesh
A Computer Engineering grad student at Stony Brook University. My passions are machine learning and android programming.
Updated on April 29, 2020Comments
-
Brahadeesh about 4 years
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.
-
Brahadeesh about 13 yearsthank you. I also want to do the reverse, as in w=my_int. is it allowed?
-
Marty about 13 yearsIt is, but you'll only get the 3 LSBs of
my_int
stored inw
. For example, if the number'd16
(10000
) is inmy_int
,w
will become=3'b000
-
Brahadeesh about 13 yearsgot it. Thank you. It means I just have to take care to keep w long enough.