Program:
Accept a number . Print its 16 bit binary representation
The code builds an appropriate array of 1s and 0s and then prints it
suppose user inputs 100 , then we fill an array at index 15 to 9 with 0 , like 0000 0000 0 till we reach 64 , we are now at index position 10, so now we have to fill 1
0000 0000 01
and we reduce the given number by 64 , so it is now 36. the next place value is 32 , we need to put 1
0000 0000 011
we reduce the number by 32 so we are left with 4
our array is built as 0000 0000 0110 0100
Then we print the array
In the iteration we have lost our original input , if you want to hold it then save it into another variable
We are also using the symbol "^" as the exponential operator in C
Note : As far as possible we refrain using magic numbers in our code and put them all as defined constant with words that explain their meaning more clearly. This improves readability of the code and also sometimes we can extend our application by just changing one or more defined values
=====================================================
# define SIXTEEN 16
# define BINARY_BASE 2
# define 16_BIT_LIMIT (BINARY_BASE ^ HEXA - 1 )
# define ONE 1
# define ZERO 0
# define SUCCESS 0
# define ERROR 1
main()
{
int degitPosition, k[SIXTEEN] , givenNumber , n ;
// Accept number
printf("Accept a number from User and print its 16 bit binary representation" ) ;
printf("Enter a positive number \(zero allowed \) less than %d :- " , 16_BIT_LIMIT ) ;
scanf("%d" , &givenNumber);
// Validate
if(givenNumber < ZERO )
{
printf("Invalid Input , Cannot accept negative numbers");
return ERROR ;
}
if(givenNumber > 16_BIT_LIMIT)
{
printf("Invalid Input , Given number exceeds %d" , 16_BIT_LIMIT");
return ERROR ;
}
/* We now fill an array with 0 or 1 depending on the place value in a 16 bit notation for this given number
*/
/* we need to loop thro all the place values in the 16 bit */
n = givenNumber ;
for ( degitPosition = SIXTEEN - 1 , degitPosition >= 0 ; degitPosition--)
{
if( n >= BINARY_BASE ^ degitPosition)
{
k[degitPosition] = ONE ;
n -= BINARY_BASE ^ degitPosition ;
}
else
k[degitPosition] = ZERO ;
}
// Now print the array
printf("\n\nthe Binary representation of %d is as follows \n\n" , givenNumber);
for( degitPosition = SIXTEEN - 1 ; degitPosition >= ZERO , degitPosition -- )
printf(%3d" , k[degitPosition]);
return SUCCESS ;
}