How Do you reset a bit value in a string?

2019-09-19 09:53发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2019-09-19 10:28

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.

 number ^= 1 << x; 

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.

查看更多
我只想做你的唯一
3楼-- · 2019-09-19 10:29

To toggle any bit in a string:

#include <limits.h>

void flip_bit(char *x, int bit_no) {
  (x + bit_no/CHAR_BIT) ^= 1 << bit_no%CHAR_BIT;
}

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 (^).

查看更多
可以哭但决不认输i
4楼-- · 2019-09-19 10:36

You have to create a bitmask, for the n-th bit, the bitmask will be:

char *bitmask = 2^(n-1);

and to flip the bit xor the string and the bitmask:

string ^= bitmask;
查看更多
ら.Afraid
5楼-- · 2019-09-19 10:42

Assuming char is 8 bits and the endian is little-endian:

char *str = ...;

str[15] ^= 0x80;

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 use 0x40. (0x01 and 0x02 for big-endian)

EDIT 2 : Here's the general case: (with the same assumptions)

char *str = ...;
int bit = 127;

int index = bit / 8;   //  Get the index
int chbit = bit % 8;   //  Get which bit in the char

int mask = 1 << chbit; //  Build the mask

str[index] ^= mask;    //  XOR to flip the bit.
查看更多
登录 后发表回答