Write a c program that converts Lower to Upper and Upper to Lower characters using bitwise.

28 Dec 2022 Balmiki Mandal 0 C Programming

C Program to Convert Lowercase Characters to Uppercase and Uppercase Characters to Lowercase Using Bitwise

"Write a program that converts Lower to Upper and Upper to Lower characters using bitwise" is an instruction to create a computer program that can take a character input from the user and convert it from lowercase to uppercase or from uppercase to lowercase using bitwise operations.

In computing, bitwise operations are operations that manipulate individual bits of a binary number. In the context of this task, the bitwise operations can be used to change the case of a character by toggling a particular bit. For example, in ASCII encoding, the difference between the uppercase and lowercase letters is a single bit, which can be toggled to convert from one case to the other.

Therefore, the program will read a character input from the user, check if it is lowercase or uppercase, and then perform the necessary bitwise operation to convert the character to the opposite case. Finally, the program will output the converted character to the user.

Program 01: C that converts lowercase characters to uppercase and uppercase characters to lowercase using bitwise operations:

#include <stdio.h>

int main() {
    char ch;

    printf("Enter a character: ");
    scanf("%c", &ch);

    if (ch >= 'a' && ch <= 'z') {
        ch &= ~(1 << 5); // convert lowercase to uppercase using bitwise
    } else if (ch >= 'A' && ch <= 'Z') {
        ch |= (1 << 5); // convert uppercase to lowercase using bitwise
    }

    printf("Converted character: %c\n", ch);

    return 0;
}

Explanation:

  • We start by reading a character from the user using the scanf() function.
  • We then check if the character is lowercase or uppercase using ASCII values.
  • If it is lowercase, we convert it to uppercase using bitwise operations. The ASCII code for 'a' is 97 and the ASCII code for 'A' is 65. The difference between the two is 32, which is the 6th bit from the right. So, we unset the 6th bit from the right using ~(1 << 5) to convert the lowercase 'ch' to uppercase.
  • If it is uppercase, we convert it to lowercase using bitwise operations. We set the 6th bit from the right using (1 << 5) to convert the uppercase 'ch' to lowercase.
  • Finally, we print the converted character using the printf() function.

Note that this program assumes that the character entered by the user is an English alphabet. If the character is not an alphabet, it will not be converted.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.