Assuming I have a register reg [15:0] my_reg
, which contains a 16-bit signed sample:
How can I find the place where the first bit change is located?
Meaning, that if assuming that my_reg = 16'b0001011011010111
, how can I know that the first change from 0
to 1
is at my_reg [12]
? Same for numbers starting with 1
,negative numbers, e.g. my_reg = 16'b1111011011010111
would be interested in the position of the first appearing 0
(which is 11
in this case).
The ultimate goal (to add a little bit of context) is to implement a digital FPGA built-in automatic gain control (AGC).
Same technique as described above but parametrized. Use XOR shifted by one bit to determine where bits change, then use a descending priority encoder to output the first change location. I stuffed with
my_reg[0]
so the first bit doesn't create a delta.Above code on EDA playground (thanks for heads up on this, BTW) http://www.edaplayground.com/x/3uP
What you need is a leading signs detector.
You can do this by performing an XOR of the 16-bit my_reg variable, then a case statement that will count the number of repeating bits, then you need to add one to this number.
For example:
if we have a four bit register, we can count the number of leading bits. You can modify this code for your purposes depending on how you want to handle what happens if all the bits are identical.
A two-liner solution for this is the following:
See a working example on edaplayground.com.
It is similar to the idea described in starbox's answer. You can model a synthesizable
log2
function using a look-up table or case statement. See edaplayground.com for a sample.