State encoding helps a digital circuit remember what it is doing by assigning simple codes to each step. It makes the circuit easier to build and understand.
State encoding (binary, one-hot, gray) in Verilog
typedef enum logic [N-1:0] {
STATE_0 = code_0,
STATE_1 = code_1,
...
} state_type;
state_type current_state, next_state;Binary encoding: Uses the smallest number of bits, counting up in binary.
One-hot encoding: Uses one bit per state, only one bit is '1' at a time.
Gray encoding: Changes only one bit between states to reduce errors.
typedef enum logic [1:0] { IDLE = 2'b00, RUN = 2'b01, STOP = 2'b10 } state_t;
typedef enum logic [2:0] { IDLE = 3'b001, RUN = 3'b010, STOP = 3'b100 } state_t;
typedef enum logic [1:0] { IDLE = 2'b00, RUN = 2'b01, STOP = 2'b11 } state_t;
This simple FSM cycles through three states using binary encoding. It moves from IDLE to RUN, then STOP, then back to IDLE.
module fsm_example( input logic clk, reset, output logic [1:0] state_out ); typedef enum logic [1:0] { IDLE = 2'b00, // binary encoding RUN = 2'b01, STOP = 2'b10 } state_t; state_t current_state, next_state; always_ff @(posedge clk or posedge reset) begin if (reset) current_state <= IDLE; else current_state <= next_state; end always_comb begin case (current_state) IDLE: next_state = RUN; RUN: next_state = STOP; STOP: next_state = IDLE; default: next_state = IDLE; endcase end assign state_out = current_state; endmodule
One-hot encoding uses more bits but can make circuits faster and simpler.
Gray encoding helps reduce errors when states change by only flipping one bit at a time.
Binary encoding is compact but may cause more complex logic for state transitions.
State encoding assigns codes to states to help digital circuits remember steps.
Binary encoding uses few bits, one-hot uses one bit per state, gray changes one bit at a time.
Choose encoding based on circuit size, speed, and complexity needs.