Search code examples
scalachiselregister-transfer-level

Power operator in Chisel


I am trying to find an equivalent of Verilog power operator ** in Chisel. I went through Chisel Cheat sheet and tutorial but I did not find what I was looking for. After going through designs written in Chisel, I found that log2xx functions are popular choice while the power operator is never used. Of course I can always use the shift operator to get power of 2 but I was hoping that there is general power operator in Chisel. I tried to use scala's math functions to the job but I got compilation error.


Solution

  • Since you are trying to calculate a bitwidth which is calculated at elaboration time (ie. when Scala is elaborating the hardware graph), we can use Scala functions. Scala only provides a power function for Doubles, but that works just fine for this case. Try math.pow(base, exp).toInt, note that base and exp can both be Ints and Scala will automatically convert them to Doubles for the function call. You simply need to convert the resulting Double to an Int for use as a bitwidth.