Pages - Menu

Monday 8 October 2012

Case conversion using bitwise operators

For a better understanding of this article, you might want to read first:

Lowercase to uppercase
By looking at the ASCII code chart, you can see that the uppercase letters have values 32 less than the ones of the lowercase letters. This means that to convert a string to uppercase, it is enough to set the sixth bit to 0. 
The C function below changes all the letters of the string received as argument to uppercase characters.
/*
 * Description:
 *  Converts all the letters of a string to uppercase using bitwise operations
 * Parameters:
 *  string - the string to be converted to uppercase
 * Returns:
 *  converted - the string converted to uppercase
 */
char *ToUppercase(char *string)
{
    char *converted = NULL;
    int  i = 0;
    converted = (char*)malloc(sizeof(char) * strlen(string) + 1);
    for(i=0; i<strlen(string); i++)
    {
        if(string[i] >='a' && string[i] <='z')
        {
            converted[i] = (char) (string[i] & 65503);//65 503 (decimal) = 1111 1111 1101 1111 (binary)
        }
        else
        {
            converted[i] = string[i];
        }
    }
    converted[i] = '\0';
    return converted;
}
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

char *ToUppercase(char *string);

int main(void)
{
    char s[] = "VINTAGE CODING";
    char *conv = NULL;
    printf("\n The string before lowercase conversion: %s",s);
    conv = ToLowercase(s);
    printf("\n\n\tThe string after lowercase conversion: %s",conv);
    getch();
    return 0;
}
Output: 

Uppercase to lowercase
For a conversion to lowercase of a string, you have to set the sixth bit to 1. The C function below changes all the letters of the string received as argument to lowercase characters.
/*
 * Description:
 *  Converts all the letters of a string to lowercase using bitwise operations
 * Parameters:
 *  string - the string to be converted to lowercase
 * Returns:
 *  converted - the string converted to lowercase
 */
char *ToLowercase(char *string)
{
    char *converted = NULL;
    int i = 0;
    converted = (char*)malloc(sizeof(char) * strlen(string) + 1);
    for(i=0; i<strlen(string); i++)
    {
        if(string[i] >= 'A' && string[i] <= 'Z')
        {
            converted[i] = (char) (string[i] | 32);//32 (decimal) = 0000 0000 0010 0000 (binary)
        }
        else
        {
            converted[i] = string[i];
        }
    }
    converted[i] = '\0';
    return converted;
}
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

char *ToLowercase(char *string);

int main(void)
{
    char s[] = "VINTAGE CODING";
    char *conv = NULL;
    printf("\n The string before lowercase conversion: %s",s);
    conv = ToLowercase(s);
    printf("\n\n\tThe string after lowercase conversion: %s",conv);
    getch();
    return 0;
}
Output:  

No comments:

Post a Comment