From 042be4b2d8a846d12c5c5dfd64f10b5caee93125 Mon Sep 17 00:00:00 2001 From: mergify[bot] Date: Wed, 19 Jan 2022 01:41:59 +0000 Subject: util: add GrayCode (#2353) (#2354) (cherry picked from commit 91d7baa8e7162d736f46b6d4964b09016d2dd172) Co-authored-by: Kevin Laeufer --- src/main/scala/chisel3/util/GrayCode.scala | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/main/scala/chisel3/util/GrayCode.scala (limited to 'src') diff --git a/src/main/scala/chisel3/util/GrayCode.scala b/src/main/scala/chisel3/util/GrayCode.scala new file mode 100644 index 00000000..ef310ee9 --- /dev/null +++ b/src/main/scala/chisel3/util/GrayCode.scala @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 + +package chisel3.util + +import chisel3._ + +object BinaryToGray { + + /** Turns a binary number into gray code. */ + def apply(in: UInt): UInt = in ^ (in >> 1) +} + +object GrayToBinary { + + /** Inverts the [[BinaryToGray]] operation. */ + def apply(in: UInt, width: Int): UInt = apply(in(width - 1, 0)) + + /** Inverts the [[BinaryToGray]] operation. */ + def apply(in: UInt): UInt = if (in.getWidth < 2) { in } + else { + val bits = in.getWidth - 2 to 0 by -1 + Cat(bits.scanLeft(in.head(1)) { case (prev, ii) => prev ^ in(ii) }) + } +} -- cgit v1.2.3