Per the LRM, the length of a string is the size of the string assigned to it. Since you don’t assign anything to s2 when it is declared, it has a size of 0. Trying to store characters to a null string should be an error.
You should first assign s1 to s2 to create a string of the correct size, then do the reverse function.
In reply to janudeep3:
You can always make an assignment to a string variable as a whole, and the target variable gets sized to hold the string (e.g.
s2=s1; or
s2=“Hello”;). The problem already mentioned with your original code is that you were trying to write to select individual characters of a string that had not been sized yet. So it was treated as an out of bounds select and nothing happens.
What is the significance of having >>8 , I tried your code with >>4 which is not working correctly.
I also increased the string : stringisgood and tried with the same code >>8 in that case also it worked fine.
Each character in a string is stored as 8 bits. So for reversing we need to use 8. If you use 4, then half of the bits gets reversed which does not give correct result. Lets take an example of a string with two characters and you can find the solution
module tb;
string s1 = "is";
string s2;
initial
begin
$display("string s1 in binary format = %b ", s1);
s2 = {<<8{s1}};
$display("reversed string=%b and string is %s", s2,s2);
s2 = {<<4{s1}};
$display("reversed string=%b and string is %s", s2,s2);
end
endmodule
Output will be
string s1 in binary format = 01101001 01110011
reversed string=01110011 01101001 and string is si
reversed string=0011 0111 1001 0110 and string is 7?
ASCII VALUE OF i is 01101001
ASCII VALUE OF s is 01110011
ASCII VALUE OF 7 is 00110111
ASCII VALUE OF ? is 10010110
Thanks for the update , I tried with <<9 , which was also giving incorrect answer. Now my understanding got clear. Irrespective of string size since each character in string gets stored by 8 bits need to use <<8 for reversing the string.