Enter integer: 16
00000000000000000000000000010000
Enter integer: -1
11111111111111111111111111111111
Enter integer: 9999
Try various values including negative and check that they are correct – the storage of signed numbers in binary was discussed in the level 1 module Computer Architecture.
You will need to use one of the shift operators (<< or >>) and the bitwise AND operator & (not &&). The basic idea is to AND a mask with the number. To give you an idea of the algorithm, suppose integers are 8 bits long rather than 32 bits and the variable data contains the number and the variable mask the mask.
Number 01110010
Mask 10000000
AND'ed = 10000000
If the result of AND'ing data with mask is non zero print a one else print a 0. Now shift the mask one bit right (>>) and repeat the AND.
number 01110010
mask 01000000
AND'ed = 01000000
Continue until the mask has been shifted eight bits right
ITS IN ANSI C . AND MASK IS MUST.
I HAVE DONE SO FAR THIS BUT CANT FIGURE OUT WHERE AND HOW TO ADD MASK.
Expand|Select|Wrap|Line Numbers
- main()
- {
- int i,n;
- for(;;)
- {
- printf("\nEnter the number\n");//number to convert
- scanf("%d",&n);
- if ( n==9999) //condition check
- return;
- else
- {
- for(i=0;i<32;i++)
- {
- printf("%d",(n<<i & 1<<31 )?1:0); //converting to binary
- }// for ends
- }//else ends
- }//for ends
- }//main ends