Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access individual bits in a char c++

Tags:

How would i go about accessing the individual bits inside a c++ type, char or any c++ other type for example.

like image 943
AnotherProgrammer Avatar asked Mar 02 '12 09:03

AnotherProgrammer


People also ask

How to read specific bits in C?

To read a bit at a specific position, you must mask out all other bits in the value. The operator that assists in that process is the bitwise & (and). After you mask out all the other bits, the value that remains is either zero or some other value.

How do I access a specific bit?

For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.

How many bits does a char have in C?

The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.

How do I extract a bit from an integer?

printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.


2 Answers

If you want access bit N:

Get: (INPUT >> N) & 1;

Set: INPUT |= 1 << N;

Unset: INPUT &= ~(1 << N);

Toggle: INPUT ^= 1 << N;

like image 127
Matt Avatar answered Oct 09 '22 11:10

Matt


You would use the binary operators | (or), & (and) and ^ (xor) to set them. To set the third bit of variable a, you would type, for instance: 

a = a | 0x4  // c++ 14 a = a | 0b0100 

Note that 4’s binary representation is 0100

like image 37
qdii Avatar answered Oct 09 '22 09:10

qdii