how to convert a char to other case in C language.
for eg. char letter='a'
then output should be A.
the problem is, it has to be done using bitwise operators.
i suppose not to use any standard library functions.
its an exercise given in "art of assembly" chapter 1 (p-63 1st problem)
for eg. ascii of a is 65 and that of A is 97
and in binary 65(A) is 0100 0001
whereas ...... 97(a) is 0110 0001
notice the sixth bit from right.
It decides the case of the letter.
I hope, NOT logic operation on this bit could change its case.
Adding 32 (0010 0000) or 20h does some work in converting.
it converts upper case to lower case.
eg. 0100 0001(A) + 0010 0000 (32)= 0110 0001(a)
But i dont know how to do so in C language.
Please help.
also help me by explaining the operators used in C to manipulate bits.
Need help in C language?
You can use the XOR (exclusive or) bitwise operator to flip the 6th bit. That will convert 'a' to 'A' and back again:
0100 0001 XOR 0010 0000 = 0110 0001
0110 0001 XOR 0010 0000 = 0100 0001
or, in decimal:
65 XOR 32 = 97
97 XOR 32 = 65
The C bitwise operator for XOR is the caret: ^
65^32 will give you 95.
97^32 will give you 65.
Reply:Hi,
Firstly you need to select only the lower case letter so we assume you can do a sample check as in
if (letter %26gt;= 'a' %26amp;%26amp; letter %26lt;= 'z')
and if it is then bitwise and as in
letter %26amp;= 0xDF
or
newletter = letter %26amp; 0xDF
Hope this helps.
Reply:I don't know C specifically, but if it's anything like C++, create a char variable, initialize it as 'a', and add 32... You can manipulate and compare chars and strings mathimatically, because that's basically how their stored
Reply:If your char is called cAlpha you would do this -
cAlpha = cAlpha %26amp; 0xdf;
or -
cAlpha %26amp;= 0xdf;
or what I tend to use -
cAlpha %26amp;= ~0x20;
This is the bitwise AND operator. It always clears bits to that are zero in its argument. The argument is often refered to as being a mask. 0xdf is '1101 1111' in binary. The sixth bit is zero the rest are set, the sixth bit of your value will be cleared, the rest will be left as they are.
In the third example I use the bitwise NOT operator '~' to create the mask. This swaps every bit in the value. In this case 0x20 (0010 0000) becomes 0xdf (1101 1111). I do this because its often easier to understand code if it shows the value that is being cleared rather than its mask.
The OR operator '|' always sets bits to one.
The XOR operator '^' swaps bits.
In the case of alpha characters you have to be careful. 'a' is 97 'z' is 122, they don't cover the entire range of number range of that bit. If you always applied the mask you will change all the chars between 96 and 127, 160 and 191, 224 and 255.
You need a piece of code that says -
if (cAlpha %26gt;= 'a' %26amp;%26amp; cAlpha %26lt;= 'z')
before the bit twiddling. Note that's a logical AND operation in the if statement.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment