One more C interview question

write a C program to set clear and toggle a bit specified!

#include <stdio.h>
#include <stdlib.h>
typedef enum
{
    set = 1,
    clear,
    toggle
}enmOperations;
int main()
{
    unsigned int setResetToggle,operations,bitposition;

    while(1)
    {
        printf("enter number bit position and operation in the followin format \n 99 1 2 \n operations supported are \n 1 - Set bit position \n 2 - clear bit position \n 3 - toggle bit postion\n");
        scanf("%d %d %d",&setResetToggle,&bitposition,&operations);

        if((bitposition <= sizeof(int) * 8) && (bitposition>0))
        {
            switch(operations)
            {
                case set:
                    setResetToggle |= (1<<(bitposition-1));
                    break;
                 case clear:
                    setResetToggle &= ~(1<<(bitposition-1));
                    break;
                case toggle:
                    setResetToggle ^= (1<<(bitposition-1));
                    break;
                default:
                    printf("small tool use it properly");
                    break;
            }
            printf("the value after operation = %d\n",setResetToggle);
        }
        else
        {
            printf("not supported bit position");
        }
    }
    return 0;
}

Result:
user@users-Computer:~/Development/SetClearTogglebitPostion$ ./main
enter number bit position and operation in the followin format
 99 1 2
 operations supported are
 1 - Set bit position
 2 - clear bit position
 3 - toggle bit postion
0 1 1
the value after operation = 1
enter number bit position and operation in the followin format
 99 1 2
 operations supported are
 1 - Set bit position
 2 - clear bit position
 3 - toggle bit postion
1 1 2
the value after operation = 0
enter number bit position and operation in the followin format
 99 1 2
 operations supported are
 1 - Set bit position
 2 - clear bit position
 3 - toggle bit postion
1 1 3
the value after operation = 0
enter number bit position and operation in the followin format
 99 1 2
 operations supported are
 1 - Set bit position
 2 - clear bit position
 3 - toggle bit postion
0 1 3
the value after operation = 1

No comments:

Post a Comment

తెలుగులో వ్రాయడానికి http://www.google.com/ime/transliteration/ ఉపయోగించండి.