zoukankan      html  css  js  c++  java
  • Grey encoder and decoder

    Author: Rui
    Reference from the website and wikipedia

    Something to mention:

    1.$display always to display the last sampled value,may cause some mismatch in the screen output

    2.parameterized module design help to scaling 

    Grey encoder

    // grey encoder, from binary input to grey output
    // algorithm:
    // from rightmost, x[i] xor x[i+1], keep the leftmost bitmodule grey_encoder#(parameter WIDTH = 4)

        (input [WIDTH - 1 : 0] bin,
        output [WIDTH - 1 : 0]grey);
    wire [WIDTH-2 : 0] temp;

    assign temp =  bin[WIDTH -1:1];
    assign grey = {bin[WIDTH-1], temp ^ bin[WIDTH -2 :0]};
    endmodule

    Grey decoder 

    //algorithm
    //keep the leftmost bit
    //b[n] = g[n], b[i] = b[i+1] xor g[i] i:0~n-2
    //pretty simple to understand, use xor 0 to keep the bit, xor 1 to invert bit
    module grey_decoder#(parameter WIDTH=4)
        (input [WIDTH-1:0] grey,
        output reg [WIDTH-1:0] bin);
    integer i;
    always@(grey) begin
        bin[WIDTH-1] = grey[WIDTH-1];
        for (i=(WIDTH-2); i>=0; i=i-1)
            bin[i] = bin[i+1] ^ grey[i];
    end
    endmodule

    Testbench

    // testbench for grey encoder
    // Author Rui Chen

    `include "grey.v"
    module grey_top;
    parameter WIDTH = 4;
    reg [WIDTH-1 : 0] bin, grey2;
    wire [WIDTH-1 : 0] grey, bin2;

    grey_encoder #(.WIDTH(WIDTH)) encoder (.bin(bin), .grey(grey));
    grey_decoder #(.WIDTH(WIDTH)) decoder (.grey(grey2), .bin(bin2));

    always@(grey) grey2 = grey;

    initial begin
        $display("debug output");
        repeat(10begin
        #3 bin = $random;
        $display("encoder part");
        $display("binary input: %b, grey output: %b", bin, grey);
        $display("decoder part");
        $display("grey input: %b, binary output: %b", grey2, bin2);
        end
        #3 $finish;
    end

    initial begin
        $dumpfile("grey.vcd");
        $dumpvars;
    end
    endmodule


    Simulation result

     

  • 相关阅读:
    05 | 深入浅出索引(下)
    04 | 深入浅出索引(上)
    03 | 事务隔离:为什么你改了我还看不见?
    02 | 日志系统:一条SQL更新语句是如何执行的?
    01 | 基础架构:一条SQL查询语句是如何执行的?
    orm的惰性机制
    简易的迁移
    rails 中 preload、includes、Eager load、Joins 的区别
    换种方式去分页
    Scala function programming
  • 原文地址:https://www.cnblogs.com/chenrui/p/2432711.html
Copyright © 2011-2022 走看看