How to specify the square of the difference of two unsigned numbers in Chisel3?

Here is one way to make this seem ugly.

class DiffSquared extends Module {
  val inputWidth = 8
  val width = 16
  val io = IO(new Bundle {
    val X = Input(UInt(inputWidth.W))
    val M = Input(UInt(inputWidth.W))
    val Out = Output(UInt(width.W))
  })
  val x = Wire(UInt((inputWidth+1).W))
  val m = Wire(UInt((inputWidth+1).W))
  x := io.X
  m := io.M
  val diff = Wire(SInt((inputWidth+1).W))
  diff := x.asSInt - m.asSInt
  io.Out := (diff*diff).asUInt
}

What is the best way to null the UInt extension for a 9-bit SInt, make a difference, squared it and present the result as a 16-bit UInt?

+4
source share
2 answers

Since not a single bit, there is a slight improvement. Should we add a null extension method to UInt to make this better? Already have there?

class DiffSquared extends Module {
  val inputWidth = 8
  val width = 16
  val io = IO( new Bundle{
    val X = Input(UInt(inputWidth.W))
    val M = Input(UInt(inputWidth.W))
    val Out = Output(UInt(width.W))
  })
  def zX(w:UInt) = Wire(UInt((w.getWidth+1).W),init=w).asSInt
  val diff = Wire(init=zX(io.X)-zX(io.M))
  io.Out := (diff*diff).asUInt
}
+1
source

There is a useful function here: zext , that zero extends UInt to SInt of width UInt + 1. Thus, you can write the code as:

class DiffSquared extends Module {
  val inputWidth = 8
  val width = 16
  val io = IO(new Bundle {
    val X = Input(UInt(inputWidth.W))
    val M = Input(UInt(inputWidth.W))
    val Out = Output(UInt(width.W))
  })
  val diff = io.X.zext() - io.M.zext()
  io.Out := (diff*diff).asUInt
}
+1
source

Source: https://habr.com/ru/post/1671834/


All Articles