如何重置字符串中的位值?

Ant*_*t's -1 c bit-manipulation

在最近的采访中我得到了这样一个问题:

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

我没有找到任何算法,但我想知道如何用C语言解决这个问题.

编辑:

在得到少数人的答案之后,我尝试了这个:

#include<stdio.h>
void main()
{
    char *str="anto";
    str[15] ^= 0x80;
    printf("%s",str);
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出为:anto.现在我的脑子里有点罢了,改变一点不会改变输出?

Kla*_*äck 10

要切换字符串中的任何位:

#include <limits.h>

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

说明:找到bit_no:th位分两步完成:

首先是所需的整个字节数(整数除法):( x + bit_no/CHAR_BIT)

然后剩下很多比特.这是通过将1乘以bit_no%CHAR_BIT位(余数)来完成的.

最后使用xor运算符(^)切换位.


Mys*_*ial 5

假设char为8位且endian为little-endian:

char *str = ...;

str[15] ^= 0x80;
Run Code Online (Sandbox Code Playgroud)

这将翻转第127位.

编辑:

如果bit-endian是big-endian,那么请0x01改用.

答案还取决于比特的编号方式.如果我们从0开始编号,则使用0x80.如果我们从1索引,那么我们使用0x40.(0x010x02为大端)

编辑2:这是一般情况:(具有相同的假设)

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.
Run Code Online (Sandbox Code Playgroud)

  • 对于每个位,如果位相同,则XOR运算符将返回0,如果它们不同则返回1.因此,如果你对1进行异或,你会翻转一下. (2认同)
  • 注意"127th bit"!="bit 127".第一位是位0,第二位是位1,等等,因此第N位是位N-1. (2认同)