Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

genlib/coding.py: binary vs. one-hot, priority coding

  • Loading branch information...
commit ecc40620715a996e57d3777f4a7cdeb2ad74697d 1 parent 48a5b86
Robert Jordens authored June 27, 2013 sbourdeauducq committed June 28, 2013

Showing 1 changed file with 55 additions and 0 deletions. Show diff stats Hide diff stats

  1. 55  migen/genlib/coding.py
55  migen/genlib/coding.py
... ...
@@ -0,0 +1,55 @@
  1
+from migen.fhdl.std import *
  2
+
  3
+"""
  4
+Encoders and decoders between binary and one-hot representation
  5
+
  6
+i: input (binary or one-hot)
  7
+o: output (one-hot or binary)
  8
+n: "none" signal (in/out), binary value is invalid
  9
+"""
  10
+
  11
+class Encoder(Module):
  12
+	def __init__(self, width):
  13
+		self.i = Signal(width) # one-hot
  14
+		self.o = Signal(max=width) # binary
  15
+		self.n = Signal() # invalid: none or multiple
  16
+		act = dict((1<<j, self.o.eq(j)) for j in range(width))
  17
+		act["default"] = self.n.eq(1)
  18
+		self.comb += Case(self.i, act)
  19
+
  20
+class PriorityEncoder(Module):
  21
+	def __init__(self, width):
  22
+		self.i = Signal(width) # one-hot, lsb has priority
  23
+		self.o = Signal(max=width) # binary
  24
+		self.n = Signal() # none
  25
+		act = If(0)
  26
+		for j in range(width):
  27
+			act = act.Elif(self.i[j], self.o.eq(j))
  28
+		self.comb += act
  29
+		self.comb += self.n.eq(self.i == 0)
  30
+
  31
+class Decoder(Module):
  32
+	def __init__(self, width):
  33
+		self.i = Signal(max=width) # binary
  34
+		self.n = Signal() # none/invalid
  35
+		self.o = Signal(width) # one-hot
  36
+		act = dict((j, self.o.eq(1<<j)) for j in range(width))
  37
+		self.comb += Case(self.i, act)
  38
+		self.comb += If(self.n, self.o.eq(0))
  39
+
  40
+class PriorityDecoder(Decoder):
  41
+	pass # same
  42
+
  43
+def _main():
  44
+	from migen.sim.generic import Simulator, TopLevel
  45
+	from migen.fhdl import verilog
  46
+
  47
+	e = Encoder(8)
  48
+	print(verilog.convert(e, ios={e.i, e.o, e.n}))
  49
+	pe = PriorityEncoder(8)
  50
+	print(verilog.convert(pe, ios={pe.i, pe.o, pe.n}))
  51
+	d = Decoder(8)
  52
+	print(verilog.convert(d, ios={d.i, d.n, d.o}))
  53
+
  54
+if __name__ == "__main__":
  55
+	_main()

0 notes on commit ecc4062

Please sign in to comment.
Something went wrong with that request. Please try again.