Lin Frank
Lin Frank

Reputation: 113

why chisel UInt(32.W) can not take a unsigned number which bit[32] happens to be 1?

It is defined that UInt is the type of unsigned integer. But in such case it seems like the MSB is still a sign. e.g., the most relative QA is Chisel UInt negative value error which works out a workaround but no why. Could you enlight me about the 'why'?

The UInt seems to be defined in chisel3/chiselFrontend/src/main/scala/chisel3/core/Bits.scala but I cannot understand the details. Is the UInt is derived from Bits and Bits is derived from Int of scala?

Upvotes: 2

Views: 1462

Answers (2)

Jack Koenig
Jack Koenig

Reputation: 6064

The issue is that Scala only has signed integers, it does not have an unsigned integer type. From the REPL

scala> 0x9456789a
res1: Int = -1806272358

Thus, Chisel only sees the negative number. UInts obviously cannot be negative so Chisel reports an error.

You can always cast from an SInt to a UInt if you want the raw 2's complement representation of a negative number interpreted as a UInt. eg.

val a = -1.S(32.W).asUInt
assert(a === "xffffffff".U)

Upvotes: 2

Chick Markley
Chick Markley

Reputation: 4051

The simple answer is that this is due to how Scala evaluates things. Consider an example like

val x = 0xFFFFFFFF.U

This statement causes an error. UInt literal are represented internally by BigInts, but the 0xFFFFFFFF is an specifying an Int value. 0xFFFFFFFF is equivalent to the Int value -1. The -1 Int value is converted to BigInt -1 and -1.U is illegal because the .U literal creation method will not accept negative values. Adding the L fixes this because 0xFFFFFFFL is a positive Long value.

Upvotes: 4

Related Questions