In the recent interview I got a question like this :
Given a string value, find out its 127th bit and reset it, do this in C language
Reset means if that particular bit is 0 change to 1 and vice versa
I didn’t find out any algorithm for this, but I want to know about how one could solve this in C language.
Edit:
After getting the answer from few, I tried this :
#include<stdio.h>
void main()
{
char *str="anto";
str[15] ^= 0x80;
printf("%s",str);
}
I get the output as : anto. Now I got strike in my head that changing a bit doesn’t change the output?
Assuming
charis 8 bits and the endian is little-endian:This will flip the 127th bit.
EDIT:
If the bit-endian is big-endian, then use
0x01instead.The answer also depends on how the bits are numbered. If we start numbering from 0, the use
0x80. If we index from 1, then we use0x40. (0x01and0x02for big-endian)EDIT 2 :
Here’s the general case: (with the same assumptions)