C / C ++ pointer type pointing to one bit?

I want to change individual data bits (e.g. int or char s). I want to do this by specifying a ptr . assigning it to some int or char, and then increasing ptr n times, I want to access the nth bit of this data. Sort of

 // 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... } 
+4
source share
6 answers

In C ++, there is no such thing as a bit pointer. You need to use two things: a byte pointer and a bit offset. This seems to be what you are referring to in your code. Here you perform separate operations with bits.

 // set a bit *ptr |= 1 << index; // clear a bit *ptr &= ~(1 << index); // test a bit if (*ptr & (1 << index)) ... 
+4
source

The smallest addressable memory block in C and C ++ is 1 byte. Thus, you cannot have a pointer to anything less than a byte. If you want to perform bitwise C and C ++ operations, you can provide bitwise operators for these operations.

+1
source

It is not possible to have the address of a single bit, but you can use structures with bit fields. Like in this example from Wikipedia like this:

 struct box_props { unsigned int opaque : 1; unsigned int fill_color : 3; unsigned int : 4; // fill to 8 bits unsigned int show_border : 1; unsigned int border_color : 3; unsigned int border_style : 2; unsigned int : 2; // fill to 16 bits }; 

Then, by manipulating individual fields, you change the sets of bits inside an unsigned int . Technically, this is identical to bitwise operations, but in this case, the compiler will generate code (and you have less chance of an error).

Keep in mind that you need to be careful when using bit fields.

+1
source

C and C ++ do not have a β€œbit pointer”, technically speaking, C and C ++ as such do not know about β€œbits”. You can create your own type, for this you need two things: a pointer to some type ( char , int - possibly unsigned) and a bit. Then you must use the pointer and bit number along with bitwise operators to actually access the values.

+1
source

There is nothing like a pointer to a bit

If you want all bits to be set to 1, then c = 0xff; is what you want if you want to set the bit under some condition:

 for(index;index<8;index++) { if (condition) c |= 1 << index; } 

As you can see, there is no need to use a pointer

0
source

You cannot read one bit from memory, the CPU always reads the full cache line, which may have different sizes for different processors.

But in terms of language you can use bit fields

0
source

All Articles