This example assumes the string is in ASCII and the English alphabet is used.
This is C99 C code, you must use the appropriate compiler flag to set this when compiling. I specifically tried not to use any libraries in this example, standard or not, because I assume that you are still learning the basics of C programming.
#define UPPER_CASE_SWITCH 0x5f void makeUpper(unsigned char *string, int length) { for(char c; length != 0 && (c=*string) != 0; --length) *string++ = (((c >= 'a' && c <= 'z')) ? (c & UPPER_CASE_SWITCH) : c); }
It exploits the fact that ONLY the difference between an upper and lower case character in an ASCII table is one bit. In particular, the 6th bit (right). All we need to do is create a βmaskβ containing all 1 except for the 6th bit (on the right), and then use the binary AND (&) instruction to apply this mask to our character. And then of course put this on our line.
Here is a python example.
>>> bin(ord("a"))
In my opinion, this is the best way to make an ASCII string (or one ASCII character) in c. Unless, of course, you need something that will return a new line, then you want to create a version of the "old" line in upper case, but you can still save the original version somewhere. This should not be too hard to do if you understand my first example. You just need to select a new array to insert a string string, and return a pointer to that array (unsigned char *).
source share