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!