MATLAB Answers

adding two fixed point numbers

2 views (last 30 days)
scc28x on 8 Apr 2021
Edited: scc28x on 16 Apr 2021
Hi, this is probably a newbie question using fixed point designer. I am trying to add two fixed point numbers, one of which is extracted partially from another fixed point number. I don't need to do any hardware code generation later on so I only care about the math being correct. Please see below:
a.bin(1:2)+b causes an error. I suppose that is because a.bin(1:2) is not a fixed point object.
I know the way to do this is to define a new fi object with the proper wordlength and then do the summation:
Is there a different way to do this so I don't need to define an intermediate fi object, c?
Thanks you very much.

Answers (1)

Andy Bartlett
Andy Bartlett on 9 Apr 2021
Bin method returns a string
The bin method of a fi object
w = a.bin(1:2)
returns a string
w =
ans =
and cannot be added to another fi object.
fi is both a constructor and a cast operator
When fi is called, it is both a constructor and a run-time cast operation.
Your goal of adding b to the two most significant bits of a without creating an intermediate variable can be achieved using fi as a cast.
wl = 3;
iMax = 2^wl - 1;
nPts = 8;
vA = randi([0 iMax],1,nPts);
vB = randi([0 iMax],1,nPts);
outFi = fi( a, 0, 2, -1, 'RoundMode', 'floor') + b
% check math to show that this is correct.
% Luxury doubles math answer and the fixed-point answer should be
% off by 0 or 1 depending on whether bit was dropped from a
outDbl = double(a) + double(b);
err = double(outFi) - outDbl;
fi_dbl_err = [
Running this script with this random number generator seed
produced the following output
outFi =
11 7 5 7 4 4 8 9
RoundingMethod: Floor
OverflowAction: Saturate
ProductMode: FullPrecision
SumMode: FullPrecision
fi_dbl_err =
11 7 5 7 4 4 8 9
12 7 6 8 4 4 9 10
-1 0 -1 -1 0 0 -1 -1
  1 Comment
scc28x on 16 Apr 2021
Thank you for your reply. I still don't quite understand the "cast" feature. Using the idea above. Here is an example:
In this case, k becomes "3" and k.bin='0110'. Maybe I missed something but this is not achieving my goal. It is merely shifting the decimal location. The underlying value of k is retained at 2.0+1=3.0.
What I want to see is:
a.bin='0010' is bit shifted to left by 1, so we get '0100'.
Now when adding 1 to "a", we get '0101'. In other words, the underlying value actually changes.
I was thinking about using bitsliceget to accomplish this. Is it the best way?
Thanks again.

Sign in to comment.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!