问题描述
我想交换寄存器变量的某些位,就像下面的例子。
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)
我尝试使用shift和mask来实现,但是发现会很复杂,有没有简单的方法
解决方法
下面的凿子 Module
完成了我认为您在这里的目标,即:翻转寄存器中的两个任意动态索引位。这将需要很多 Mux
来完成,但我认为这个例子表明 chisel 可以非常干净地生成这些。基本策略是将寄存器视为 Vec
的布尔值,然后根据该位是否被引用为两个位地址之一,为这些布尔值中的每一个创建一个 Mux
到任何其他位。
然后使用 Vec
将生成的序列转换为新的 VecInit
,然后将该 vec
转换为 UInt
并将其连接回 reg
。
这个模块有一些额外的代码来加载寄存器。您可能想以其他方式做到这一点。
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
}