(A) Problem Statement :
Write a program to display the internal representation of
integers.
(B) Input and Output :
This program takes an integer value as input and gives it’s
internal representation, that is if it is positive number then it’s
binary representation and if it is negative number then it’s 2’s
complement in 32-bits.
(i) enter the integer value : 12
00000000000000000000000000001100
(ii) enter the integer value : -6
11111111111111111111111111111010
(C) Examples :
(i) the internal representation of 12 is in binary form
• 12%2=0 and n=12/2=6
• 6%2 = 0 and n=6/2 =3
• 3%2 = 1 and n = 3/2 =1
• 1%2 = 1 and n = 1/2 = 0
The remaining bits are all 0’s
Internal representation is 000000000000000000000000000001100
(ii) the internal representation of -6 is in 2’s complement form
~(binary representation of 6)+1
• 6%2 = 0 and n=6/2 =3
• 3%2 = 1 and n = 3/2 =1
• 1%2 = 1 and n = 1/2 = 0
The binary equivalent for -6 is
000000000000000000000000000110
The one’s complement is
11111111111111111111111111111001
The two’s complement is
11111111111111111111111111111010
(D)Algorithm :
Step 1: start
Step 2: read the integer value n and initialize array a
of size 32 with 0’s.
Step 3: if n >0 then repeat the step4 and 5 till the
value of n is greater than 0 .
Step 4: start from I value 0 and increment it by 1
After step 5.
Step 5: a[i] = n%2 and n = n/2;
Step 6 : if n<0 then repeat the following step7 and 8
till the value of n is greater than 0 .
Step 7: start from I value 0 and increment it by 1
After step 5.
Step 8: a[i] = (n%2+1)%2 and n = n/2;
Step 9: print the array from 31 to 0.
Step 10: Stop
(E) Program :
#include
#include
void internal(long long int n)
{
int a[32]={0},i,j;
if(n>0) //if n is positive number
{
for(i=0;n>0;i++) //finds binary representation
{
a[i]=n%2;
n/=2;
}
}
if(n<0) //n is negative number
{
for(i=0;i<32;i++)
{
a[i]=((n%2)+1)%2; //finds 2's complement
n /=2;
}
for(i=0;i<32;i++) //and displays
{
a[i] = a[i]+1;
if(a[i]>1)
a[i]=0;
else
break;
}
}
for(j=31;j>=0;j--) //display for n>0
printf("%d",a[j]);
printf("\n");
}
void main()
{
long long int n;
clrscr(); //read the integer value
printf("\n enter the integer value:");
scanf("%lld",&n);
internal(n); //call internal function
getch();
}
(F) Testing :
The program can be tested for any integer value and
represented in 32-bit binary form.
(G) Limitations :
(i) it can give representation of 4294967295.
No comments:
Post a Comment