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?
1st is you are asking is says as toggle not reset okey
To toggle a bit
The XOR operator (^) can be used to toggle a bit.
That will toggle bit x. for more info of such think read this
Now as you know string is number of character & size of 1 charachter is 1 byte so now which ever bit you want to toggle that put instead of X in and string in place of number.
To toggle any bit in a string:
Explanation: Finding the bit_no:th bit is done in two steps:
First as many whole bytes as required (integer division): (x + bit_no/CHAR_BIT)
Then as many bits that are left over. This is done by shifting a 1 by bit_no%CHAR_BIT bits (the remainder).
Finally toggle the bit using the xor operator (^).
You have to create a bitmask, for the n-th bit, the bitmask will be:
and to flip the bit xor the string and the bitmask:
Assuming
char
is 8 bits and the endian is little-endian:This will flip the 127th bit.
EDIT:
If the bit-endian is big-endian, then use
0x01
instead.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
. (0x01
and0x02
for big-endian)EDIT 2 : Here's the general case: (with the same assumptions)