in Digital Logic recategorized by
1,875 views
19 votes
19 votes

The following is an incomplete Pascal function to convert a given decimal integer (in the range $-8$ to $+7$) into a binary integer in $2$’s complement representation. Determine the expressions $A, B, C$ that complete program.

function TWOSCOMP (N:integer):integer;  
    var  
    REM, EXPONENT:integer;  
    BINARY :integer;  
    begin  
        if(N>=-8) and (N<=+7) then   
        begin
            if N<0 then  
                N:=A;  
            BINARY:=0;
            EXPONENT:=1;
            while N<>0 do
            begin
                REM:=N mod 2;
                BINARY:=BINARY + B*EXPONENT;
                EXPONENT:=EXPONENT*10;
                N:=C 
            end
            TWOSCOMP:=BINARY
        end  
    end;
in Digital Logic recategorized by
1.9k views

4 Comments

it means to return value of BINARY (TWOSCOMP is the function name)
1
1

I think there is a typing mistake in this line

BIANRY:=BINARY + B*EXPONENT;

I think it should be BINARY

0
0

2 Answers

7 votes
7 votes
Best answer
$A=16+N, ($for $N = -1, A = 15$ which is the largest value, for $N = -8, A = 8)$

$B=\text{REM}$

$C=N/2$
edited by

4 Comments

got it thanks
0
0
Can someone explain why is "N+16" even working? Is there any logical reason behind it or it just some pattern that we were able to find.
0
0

This is based on the concept of b’s complement and (b + 1)’s complement of a base b number.

These are the respective formulae for finding the complements of a n-digit number let’s say X:


b’s complement of X =  (b^n – 1 ) – X


(b+1)’s complement of X = b^n – X 


For binary(base 2) we have 1’s and 2’s complement. For a n-bit number X:

 

1’s complement of X = (2^n – 1) – X

 

2’s complement of X = 2^n – X

 

We know the range of 2’s complement for a n-bit number is from -2^(n – 1) to +2^(n – 1) – 1.

 

For the range -8 to +7 we can see that n = 4

 

 

For representing negative numbers in 2’s complement: 

2^n – absolute value of X

 

e.g. in the question lets represent -8

 

2^n – 8 = 2^n + (-8) = 2^4 + (-8) = 16 + (-8)


So in this way we are adding 16 to it to get the 2’s complement representation.

1
1
3 votes
3 votes
for A:

Since negative number can come as (-8,-7,-6.....-1)

and 2's complement number is used for n=4.

so corresponding binary representation will be: N+2^4 = N+16.

for B:

Concatenation is used here BINARY : BINARY + B * EXPONENT

so whatever remainder will come in above stage which is REM will be used here so B=REM

for C:

here value of N will be divided by 2 and remainder will be assign in N (Updation of N is done here)

so C= N/2.
edited by

Related questions