How to exchange certain bits of the register

Viewed 68

I want to exchange certain bits of a register variable, just like the following example.

val data = Reg(UInt(100.W))
val re_order1 = Wire(UInt(log2Ceil(100).W))
val re_order2 = Wire(UInt(log2Ceil(100).W))
//Exchange the bits of the data register in re_order1 and re_order2
data(re_order1) := data(re_order2)
data(re_order2) := data(re_order1)

I tried to use shift and mask to achieve, but found it will be very complicated, is there a simple way

1 Answers

The following chisel Module does what I think you are aiming for here, that is: flip two arbitrary dynamically indexed bits in a register. This is going to require a lot of Muxes to accomplish this but I think this example shows that chisel can generate those pretty cleanly. The basic strategy is to treat the register as a Vec of bools then create a Mux every one of those bools to any other bit, based on whether the bit is referenced as one of the two bit addresses. Then convert the sequences of generated as a new Vec using VecInit and then convert that vec to a UInt and wire it back into reg.

This module has a little bit of additional code to load the register. You may want to do that some other way.

import chisel3._
import chisel3.util.log2Ceil
import chiseltest._
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers

class FlipBits(bitWidth: Int) extends Module {
  val io = IO(new Bundle {
    val load = Input(Bool())
    val loadValue = Input(UInt(bitWidth.W))
    val bitAddress1 = Input(UInt(log2Ceil(bitWidth).W))
    val bitAddress2 = Input(UInt(log2Ceil(bitWidth).W))
    val out = Output(UInt(bitWidth.W))
  })

  val reg = RegInit(0.U(bitWidth.W))
  val bits = VecInit(reg.asBools())

  when(io.load) {
    reg := io.loadValue
  }.otherwise {
    reg := VecInit(bits.indices.map { index =>
      val index1 = Mux(index.U === io.bitAddress1, io.bitAddress2, index.U)
      val index2 = Mux(index.U === io.bitAddress2, io.bitAddress1, index1)
      bits(index2)
    }).asUInt
  }

  io.out := reg
}
Related