title: Formatting Dynamic Array of Bits as String in SystemVerilog
body: <p>How can I format a dynamic array of bits (or more correctly, logics) as a string, e.g., for UVM's convert2string?  For example, I would like to convert</p>
  
  <pre><code>logic        vdyn[];  
  ...  
  vdyn = new [16] ('{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1});  
  </code></pre>
  
  <p>to the string <code>0097</code>.</p>
  
  <p>I thought the following would work (the <code>#</code> are just to delimit the string for readability):</p>
  
  <pre><code>  fmt = $sformatf("#%%%0dh#", (vdyn.size-1)/4 + 1); // "#%4h#"
    vstr = $sformatf(fmt, { &gt;&gt; {vdyn}});
  </code></pre>
  
  <p>but it returns <code>#   x#</code>, at least in Questa 10.3d (I suspect this is a bug - I'd be interested if it works on other simulators).</p>
  
  <p>I tried converting it to a packed array first, but that runs into other problems.  Without a size constraint on the result, the source value always gets left-justified in the destination variable, e.g.:</p>
  
  <pre><code>logic [63:0] v64;
  ...
  v64 = {&gt;&gt; {vdyn}}; // 64'h0097000000000000
  </code></pre>
  
  <p>There's no way to print out just the part I want without using variable-size slices.  The following works, but it requires that I know the size of the array at compile time:</p>
  
  <pre><code>v64 = 16'({&gt;&gt; {vdyn}});  // 64'h0000000000000097
  </code></pre>
  
  <p>The best thing I've found is the following "double-reverse" (note that I'm using <code>&lt;&lt;</code> here, not <code>&gt;&gt;</code>):</p>
  
  <pre><code>     v64 = {&lt;&lt; {vdyn}};    // 64'he900000000000000 
       v64 = {&lt;&lt; {v64}};     // 64'h0000000000000097
       vstr = $sformatf(fmt, v64); // #0097#
  </code></pre>
  
  <p>It seems kind of hokey to have to do this, though.  By the way, combining the first two statements into one doesn't work:</p>
  
  <pre><code>     v64 = {&lt;&lt; {{&lt;&lt; {vdyn}}}};     // 64'hZ900000000000000
  </code></pre>
  
  <p>(<code>v64[63]</code> is <code>z</code> for some reason).  Again, I suspect this is a bug in Questa 10.3d.</p>