Sunday 4 August 2013

INTERNAL REPRESENTATION OF BIT PATTERN OF INTEGERS

QUES:-
Display the internal representation of bit pattern of integerrs and observe and find the representation of negative numbers;
ANS:-
/*******************************************************************************/
#include<stdio.h>
#include<conio.h>

void decimal_to_binary(unsigned int);

int main()
{
int n;

clrscr();

printf("ENTER THE NUMBER FOR WHICH YOU WANT THE INTERNAL REPRESENTATION OF BIT PATTERN\n");
scanf("%d",&n);

decimal_to_binary((unsigned int)n);
getch();
return 0;
}

void decimal_to_binary(unsigned int n)
{
int *arr;
int counter;
int i;
counter=sizeof(int)*8;
/*
now counter represents the number of
bits that are used to store an integer on
your compiler
*/
arr=(int *)malloc(sizeof(int)*counter);

for(i=counter-1;i>=0;i--)
{
if(n%2==0)
arr[i]=0;
else
arr[i]=1;
n/=2;
}

for(i=0;i<counter;i++)
printf("%d",arr[i]);

}
/*******************************************************************************/

ALTERNATE SOLUTION:-
/*******************************************************************************/
#include<conio.h>
#include<stdio.h>

void decimal_to_binary(unsigned char);

union u
{
int i;
char c;
};

int main()
{
char*ptr;
union u a;

printf("ENTER AN INTEGER : \n");
scanf("%d",&a.i);

ptr=&a.i;

ptr++;
decimal_to_binary(*ptr);

ptr--;
decimal_to_binary(*ptr);

getch();
return 0;
}

void decimal_to_binary(unsigned char n)
{
int arr[8];
int i;

for(i=7;i>=0;i--)
{
if(n%2==0)
arr[i]=0;
else
arr[i]=1;
n/=2;
}

for(i=0;i<8;i++)
printf("%d",arr[i]);
printf(" ");
}
/*******************************************************************************/

No comments:

Post a Comment