Janus Troelsen
Janus Troelsen

Reputation: 21300

Pythonesque bit-slicing in Verilog?

In Python, I can select even or odd bits like this:

>>> bits = ['a','b','c','d'];
>>> bits[0::2]
['a', 'c']
>>> bits[1::2]
['b', 'd']

It would be very practical if I could do this in Verilog, so that I wouldn't have to expand the expression and do it manually. Expanded (i.e. {a[0], a[2]} and {a[1], a[3]}), it obviously wouldn't work with my otherwise parameterized wire set.

Upvotes: 4

Views: 2474

Answers (2)

dwikle
dwikle

Reputation: 6978

There is no mechanism in Verilog or SystemVerilog to do a bit slice like the Python example you gave. That is, you cannot specify a step of 2 between bits.

You can do this with a for-loop, and it doesn't need to be in a generate block like in your own answer.

Modified example from your answer:

always @(*) begin
   for (int i = 0; i < FLOORS; i++) begin
      RELEVANT[i] <= FLOOR_REQUEST[i*2+FORWARD];
   end
end

This should synthesize okay as long as FLOORS is a constant.

Upvotes: 2

Janus Troelsen
Janus Troelsen

Reputation: 21300

It can be done with a generate block. Example:

wire [FLOORS-1:0] RELEVANT;

genvar i;
generate
    for (i=0; i<FLOORS; i=i+1) begin
        assign RELEVANT[i] = FLOOR_REQUEST[i*2+FORWARD];
    end
endgenerate
  • FLOORS is the width of the output wire (half the width of the input wire).
  • RELEVANT is the result.
  • FORWARD is the even/odd selector (0 or 1).
  • FLOOR_REQUEST is the input.

Upvotes: 1

Related Questions