Given a string, write a function that returns toggle case of a string using the bitwise operators in place.
In ASCII codes, character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2. Similarly, character ‘D’ is integer 68 = (0100 0100)2, while character ‘d’ is integer 100 = (0110 0100)2.
As we can see, only sixth least significant bit is different in ASCII code of ‘A’ and ‘a’. Similar behavior can be seen in ASCII code of ‘D’ and ‘d’. Therefore, we need to toggle this bit for toggling case.
Input : "GeekSfOrgEEKs" Output : "gEEKsFoRGeekS" Input : "StRinG" Output : "sTrINg"
The ASCII table is constructed in such way that the binary representation of lowercase letters is almost identical of binary representation of uppercase letters.
The integer with 6th LSB as 1 is 32 (0010 0000). Therefore, bitwise XORing of a character with 32 will toggle the 6th LSB of character and hence, will toggle its case. If character is upper case, it will be converted to lower case and vice versa.
Toggle case: cHErRy Original string: CheRrY
Thanks to Kumar Gaurav for improving the solution.
Similar Article :
Case conversion of a string using BitWise operators in C/C++
This article is contributed by Sanjay Kumar Ulsha from JNTUH College Of Engineering, Hyderabad. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in C/C++
- Python | Toggle characters in words having same case
- Bitwise Operators in C/C++
- What are the differences between bitwise and logical AND operators in C/C++?
- Bitwise right shift operators in Java
- Check if a number is divisible by 8 using bitwise operators
- Check if a number is multiple of 9 using bitwise operators
- Check if a number is divisible by 17 using bitwise operators
- Russian Peasant (Multiply two numbers using bitwise operators)
- Program to toggle all characters in a string
- String in Switch Case in Java
- Permute a string by changing case
- Sentence Case of a given Camel cased string
- Convert characters of a string to opposite case
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Improved By : nitin mittal