C Program to Change the case of an Alphabet using Bit Manipulation


 

// Program by Akash Tripathi (@proakash256) 
 
// A = 00001000001
// a = 00001100001

// So to change A to a we need to
// set the bit at 6th position and
// vice versa.

#include <stdio.h>
int main()
{
    char c , result;
    printf("Enter the Alphabet : ");
    scanf("%c" , &c);
    
    //For UpperCase to LowerCase
    if(c >= 'A' && c <= 'Z')
    {
        // In this Method, we
        // left shift(<<) 1 5 times
        // and then OR(|) it with n
        // But (1 << 5) in ASCII Code
        // represents a Space.

        result = (c | ' ');
        printf("\nThe LowerCase of %c is %c.",
                 c , result);
    }
    
    //For LowerCase to UpperCase
    if(c >= 'a' && c <= 'z')
    {
        // In this Method, we
        // left shift(<<) 1 5 times,
        // negate it and then AND(&) it with n
        // But if the zeroes after the MSB,
        // do not change, then also it will work.
        // So we need to & it with (00001011111)
        // which in ASCII Code represents '_'.

        result = (c & '_');
        printf("\nThe UpperCase of %c is %c.", 
                c , result);
    }
    return 0;
}

Comments