我想修改单个数据位(例如ints或chars).我想通过制作指针来做到这一点,比方说ptr.通过将其分配给某个int或char,然后在递增ptrn次之后,我想访问该数据的第n位.就像是
// If i want to change all the 8 bits in a char variable
char c="A";
T *ptr=&c; //T is the data type of pointer I want..
int index=0;
for(index;index<8;index++)
{
*ptr=1; //Something like assigning 1 to the bit pointed by ptr...
}
Run Code Online (Sandbox Code Playgroud)
在C++中没有比特指针这样的东西.你需要使用两个东西,一个字节指针和一个偏移量.这似乎是你在代码中所面对的.以下是您执行单个位操作的方法.
// set a bit
*ptr |= 1 << index;
// clear a bit
*ptr &= ~(1 << index);
// test a bit
if (*ptr & (1 << index))
...
Run Code Online (Sandbox Code Playgroud)