Search code examples
scalaone-hot-encodingchisel

Implement a Verilog $onehot task in Chisel


Is there a straightforward way to check a 1-hot bus encoding in Chisel?

My current solution seems a bit ugly. Can I do better?

val range = Output (Vec (num, Bool()))
val outSum = io.range map ( p => if ( p == true.B ) 1.U else 0.U ) reduceleft (_ + _)

// This is $onehot0
assert (outSum <= 1.U, "One-hot0 bus encoding failed")

// This is $onehot
assert (outSum == 1.U, "One-hot bus encoding failed")

Solution

  • You could use PopCount

    import chisel3._
    import chisel3.util.PopCount
    
    ...
    
    val io = IO(new Bundle {
      val range = Output(Vec(num, Bool()))
    })
    val outSum = PopCount(io.range)
    // assertions...