2

I want to display first 5 characters, but in my code it displays from end:

module TEST_gate;
reg[8*5:1]str1;
initial begin 
str1="HelloWorld";
$display("str1= %s",str1);

I want to display Hello but it displays World.

2 Answers 2

3

Your reg is not wide enough to hold all 10 characters of your string. To store all characters, change:

reg[8*5:1]str1;

to:

reg[8*10:1]str1;

Refer to IEEE Std 1800-2017, section 5.9 String literals.

A string literal can be assigned to an integral type, such as a packed array. If the size differs, it is right justified. To fully store a string literal, the integral type should be declared with a width equal to the number of characters in the string multiplied by 8.

Then you need to select a range according to the 1st 5 characters for your display.

If you enable SystemVerilog features in your simulator, you can use the string data type instead:

module tb;

reg[8*10:1]str1;
string str2;

initial begin 
    str1="HelloWorld";
    str2="HelloWorld";
    $display("str1= %s",str1);
    $display("str1= %s",str1[80:41]);
    $display("str2= %s",str2);
    $display("str2= %s",str2.substr(0,4));
end

endmodule

Prints:

str1= HelloWorld
str1= Hello
str2= HelloWorld
str2= Hello

Refer to section 6.16.8 Substr().

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

Comments

1

In Verilog, string literals are just packed arrays of bits (or a bit-vector), each character is 8 ASCII bits. The left most bit of the first character in a string is the MSB of the vector and the right most bit of the last character is the LSB of the vector.

Your "HelloWorld" string literal is 10 characters repressing an 80-bit packed array and you are trying to assign it to a 40 bit variable. With any assignment from a larger to smaller integral variable, Verilog right justifies and silently truncates the bits to the left, in your case the bits representing "Hello".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.