C/C++指针类型指向单个位?

tig*_*den 4 c c++ pointers

我想修改单个数据位(例如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)

joh*_*ohn 5

在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)


Alo*_*ave 1

C和C++中最小的可寻址内存单元是1字节。所以你不能有一个指向任何小于字节的指针。如果你想执行按位运算,C 和 C++ 为这些操作提供了按位运算符