Streamlining of zeroing out last 2 bits of fixed 16 bit number?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Imola Fodor
am 24 Okt. 2023
Bearbeitet: Andy Bartlett
am 25 Okt. 2023
Would setting correctly the parameters of quantizer object be the solution when the goal is to perform bit truncation of fixed 16 bit, to get left with 14 bit of significant bits, and 0s on last two bits?
I don't know the fraction length to be used, but we can suppose that the binary point is on the extreme left, since all numbers are <1. Tried something like this, just to get the same bit representation as with bitshifts:
q = quantizer('fixed','floor',[14 20]);
x_trunc= quantize(q, x)
Streamlining is needed to avoid for loops with eg. double bitshift:
bitshift(bitshift(fi(x, 1, 16), -2), 2))
so any solution is welcomed. Thank you
0 Kommentare
Akzeptierte Antwort
Andy Bartlett
am 25 Okt. 2023
Bearbeitet: Andy Bartlett
am 25 Okt. 2023
There are 3 ways this can be achieved.
As already discussed, Bitwise AND against a constant mask or shift right then shift left.
A third approach is to cast to a type with fewer fraction bits with round toward floor, then cast back to the original type.
For power of two scaling (aka binary point scaling), the pair of shifts and pair of cast are equivalent and will generate identical C code.
I would not recommend directly using quantizer. Using casts is an equivalent concept and the more natural way to perform the operation for fi objects.
Input
format long
nBitsDrop = 2;
wl = 16; % word length
fl = 16; % fraction length
slope = 2^-fl;
uDbl = slope * ( (2^(wl-2) - 1) - 2.^(3:5) ).';
u = fi(uDbl,0,wl,fl)
u.bin
Bitwise AND with constant mask
maskDbl = (2^wl - (2^nBitsDrop)) * slope;
mask = cast( maskDbl, 'like', u)
mask.bin
y1 = bitand(u,mask)
y1.bin
Pair of Shifts
temp2 = bitsra( u, nBitsDrop)
temp2.bin
y2 = bitsll( temp2, nBitsDrop)
y2.bin
Pair of Casts
Key is that first cast has a fraction length that is nBitsDrop bits shorter, and the cast rounds toward Floor.
temp3 = fi( u, 0, wl, fl-nBitsDrop, 'RoundingMethod','Floor');
temp3 = removefimath( temp3 )
temp3.bin
y3 = cast( temp3, 'like', u )
y3.bin
0 Kommentare
Weitere Antworten (1)
dpb
am 24 Okt. 2023
I have no knowledge of how Fixed-Point Designer stores stuff, but can you not do something like
x=bitand(x,0xFFFC)
?
2 Kommentare
Siehe auch
Kategorien
Mehr zu Create Fixed-Point Objects in MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!