Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

16
Feb

ASCII Case Conversion

Related Blog Items

/*
 * case_conv.c  -   Program to change case without using arithmetic
 *                  operators or library functions.  This program
 *                  works ONLY if the charcter set is ASCII, and hence
 *                  is not portable.  It is here, only as an example,
 *                  to convey a logic as how it can be done.
 */

/*
 * Refer the ASCII table while tracing the following program:
 *
 * Letter           Upper(binary)       Lower(binary)
 * ——           ————-       ————-
 *
 *  A               0100 0001           0110 0001
 *  B               0100 0010           0110 0010
 *  …             …                 …
 *  O               0100 1111           0110 1111
 *  P               0101 0000           0111 0000
 *  …             …                 …
 *  Z               0101 1010           0111 1010
 */

#include <stdio.h>
#include <stdlib.h>

int
to_lower ( int ch )
{
    unsigned char _ch = (unsigned char)ch >> 4;

    /* If CH is already in lower case, return it */
    if ( _ch == 0×6 || _ch == 0×7 )
        return ch;

    /* convert it to lower case */
    if ( _ch == 0×4 )
        return (int)( ( (unsigned char)ch & 0×0f ) | 0×60 );
    else
    if ( _ch == 0×5 )
        return (int)( ( (unsigned char)ch & 0×0f ) | 0×70 );
    else
        return ch;
}

int
to_upper ( int ch )
{
    unsigned char _ch = (unsigned char)ch >> 4;

    /* If CH is already in upper case, return it */
    if ( _ch == 0×4 || _ch == 0×5 )
        return ch;

    /* convert it to upper case */
    if ( _ch == 0×6 )
        return (int)( ( (unsigned char)ch & 0×0f ) | 0×40 );
    else
    if ( _ch == 0×7 )
        return (int)( ( (unsigned char)ch & 0×0f ) | 0×50 );
    else
        return ch;
}

int
main ( void )
{
    printf ( "%c\n", to_upper ( ‘+’ ) );
    printf ( "%c\n", to_upper ( ‘r’ ) );
    printf ( "%c\n", to_upper ( ‘l’ ) );
    printf ( "%c\n", to_upper ( ‘P’ ) );

    printf ( "%c\n", to_lower ( ‘$’ ) );
    printf ( "%c\n", to_lower ( ‘R’ ) );
    printf ( "%c\n", to_lower ( ‘O’ ) );
    printf ( "%c\n", to_lower ( ‘9′ ) );
    return EXIT_SUCCESS;
}

Popularity: 11%

You need to log on to convert this article into PDF


Related Blog Items

2 Comments

  • Asthra  said:

    eventhough no performance gain (same amount of time as normal algo) but this algo has good (and new (to me atleast)) logic.. thanks


  • Vijay Zanvar  said:

    As you have correctly said, this program has no real-time use. It should be taken as a different way of approaching the probelm and learning bit operations.


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image