Change case of a character using bit manipulation in C++

hello everyone, in this tutorial, we will learn about how to change the case of a character using bit manipulation in C++.
before we start do you know, What is the meaning of change case of a character?

it means changing LOWERCASE TO UPPERCASE & UPPERCASE TO LOWERCASE.

let’s see an example
UPPERCASE TO LOWERCASE: 

Uppercase: A
Lowercase: a

LOWERCASE TO UPPERCASE:

Lowercase: a
Uppercase: A

Logic to change the case of a character

ALPHABET                         BINARY FORM                   ASCII CODE

A                             1000001                       65
a                             1100001                       97

B                             1000010                       66
b                             1100010                       98

C                             1000011                       67
c                             1100011                       99

It is the Binary representation of Alphabet’s in Uppercase and their Lowercase, every character is stored in memory as their ASCII code.

  1. Lowercase to Uppercase:  First of all clear the 5th bit of the given character because if you look in the binary representation of alphabet’s, you’ll find that Only 5th bit is different in the Uppercase and Lower case of a particular character.
    to clear 5th bit, you can use BITWISE AND operation (&).
    because the binary form of ‘a’ is 1100001 and ASCII code is 97
    same as the binary form of ‘_’ (underscore) is 1011111 and ASCII code is 95
    if you perform AND operation between ‘a’ and ‘_’,
    ‘a’ &  ‘_’ = 1000001 in binary and in ASCII code 65.
    1000001 is the binary form and 65 is the ASCII code of ‘A’ which is Uppercase of ‘a’.
  2.  Uppercase to lowercase: in this case, you can use BITWISE OR operation (|).
    the binary form of ‘A’ is 1000001 and ASCII code is 65, and the binary form of space (‘ ‘) is 0100000 and  ASCII code is 32, so space is equivalent to (1 << 5)
    if you perform OR operation between ‘A’ and ‘  ‘,
    A | 32 = 1100001 in binary and in ASCII code 97.
    1100001 is the binary form and 97 is the ASCII code of ‘a’ which is lowercase of ‘A’.

C++ Program to Change case of a character using bit manipulation

#include <iostream>
using namespace std;

char UpperToLower(char c)
{
  return (c | ' ');
}

char LowerToUpper(char c)
{
  
  return (c & '_');
}


int main()
{
  char c;
  cout << "Enter upper case Character: ";
  cin >> c;
  cout << "Result :  "  << UpperToLower(c);
  cout << "\nEnter lower case Character: ";
  cin >> c;
  cout << "Result :  "  << LowerToUpper(c);

  return 0;
}

output:




Enter upper case Character: A
Result : a
Enter lower case Character: a
Result : A

do let me know in the comment section if you have any doubt.

Also read: check if a number is a palindrome or not in c++


Leave a Reply

Your email address will not be published. Required fields are marked *