1
$\begingroup$

I am working on signed 2's complement for my fractions coefficients. Below code can be used for positive inputs. However for a negative 2's complement when I added LSB with 1, then an error pops. I think it is because of overflow. Now How can I convert negative coefficients using 2's complement for I and F of 3 and 9? and how to deal with overflow?

a = 0.7; % coefficient (actually for -0.7)
n = 3;         % number bits for integer part of your coefficient      
m = 9;         % number bits for fraction part of your coefficient
% binary number
de2bi = fix(rem(a*pow2(-(n-1):m),2)); 
% signed 2's complement for negative numbers
negadd = [1];
negadd = [negadd, zeros(1, length(de2bi) - length(negadd))];
flipadd = fliplr(negadd);
magsig = fliplr(de2bi(bi2de(fliplr(de2bi))+bi2de(fliplr(flipadd))));
% back to binary
b2d = magsig*pow2(n-1:-1:-m).';
$\endgroup$
1
$\begingroup$

If your routine works correctly for converting positive numbers, you could just use it to convert a negative number by first adding the value of the sign bit (MSB) to the negative number (which must make it positive if it is not out of range), then convert the resulting positive number, and finally add the sign bit.

Example: convert the number $-0.7$ to Q3.9 format. The MSB has a value of $-2^2=-4$, so we first convert the number $-0.7+4=3.3$, which results in

011.010011010 ($= 3.30078125$)

Now you just add the sign bit and you obtain the representation of the original number:

111.010011010 ($=-0.69921875$)

| improve this answer | |
$\endgroup$
  • $\begingroup$ Yes, I did that. What about the overflow? Some of my filter coefficients when the used the above code results in overflow. How can I fix that? $\endgroup$ – hari Jul 22 at 19:51
  • $\begingroup$ @hari: You know the range of values of your filter coefficients, so you can only get overflow if you chose the wrong number format. Just choose a format that can represent the largest value (in magnitude) of your coefficients. $\endgroup$ – Matt L. Jul 22 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.