signed 2's complement of a negative number for Integer = 3 and Fraction = 9 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).';
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$)