Can you define a bit slice in Verilog?

For example, is this possible:

`define opcode 5:3  // is this possible?

reg [ 7:0 ] a, b;


if ( a[ `opcode ] == someValue )  // a[5:3]


if ( b[ `opcode ] == someValue )  // b[5:3]


2 Answers 2


You can `define almost any text you want. You would have to use a[`opcode] with the backtick.

SystemVerilog gives you some other options.

The let construct declares a name for an expression.

let opcode = a[5:3];
if (opcode==someValue)

You can use a packed struct.

struct packed {
   logic [1:0] field1;
   logic [2:0] opcode;
   logic [2:0] field2;
} a;

Now you can refer to a.opcode as the same as a[5:3].

  • \$\begingroup\$ shouldn't it be logic [5:3] opcode;? - Ah wait, no, it's packed. of course. I presume that order of definition matters. - Is there another kind of struct for doing what I just said? some absolute addressing? \$\endgroup\$ Sep 24, 2018 at 6:17
  • \$\begingroup\$ Ah oops, added the backticks \$\endgroup\$
    – Jet Blue
    Sep 24, 2018 at 6:17
  • \$\begingroup\$ @HarrySvensson, you could do it that way if you wanted. But if you do absolute addressing, you have to remember to access your fields with the absolute indexing. In fact, if you never plan to access the individual bits of your fields, that might be a better way of doing it. \$\endgroup\$
    – dave_59
    Sep 24, 2018 at 17:36

Yes, you can.

But it's probably cleaner and easier to simply break the register into fields using wires:

wire [2:0] a_opcode = a[5:3];

if (a_opcode == someValue) ...

How many different registers are you going to be extracting opcodes from?

  • 3
    \$\begingroup\$ Note that this solution only works for reading a_opcode, not writing to it. Most of the time, that is OK. \$\endgroup\$
    – dave_59
    Sep 24, 2018 at 5:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.