Streamlining of zeroing out last 2 bits of fixed 16 bit number?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Andy Bartlett
2023-10-25
编辑:Andy Bartlett
2023-10-25
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 个评论
更多回答(1 个)
dpb
2023-10-24
I have no knowledge of how Fixed-Point Designer stores stuff, but can you not do something like
x=bitand(x,0xFFFC)
?
2 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Create Fixed-Point Objects in MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!