AnotherProgrammer
AnotherProgrammer

Reputation: 368

Access individual bits in a char c++

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

Upvotes: 23

Views: 47629

Answers (4)

Oyebola
Oyebola

Reputation: 151

If you want to look at the nth bit in a number you can use: number&(1<<n).

Essentially the the (1<<n) which is basically 2^n(because you shift the 1 bit in ...0001 n times, each left shift means multiply by 2) creates a number which happens to be 0 everywhere but 1 at the nth position(this is how math works).

You then & that with number. This returns a number which is either 0 everywhere or a number that has a 1 somewhere(essentially an integer which is either 0 or not).

Example: 2nd bit in in 4, 4&(1<<2)

  0100
& 0010
  ____
  0000 = 0

Therefore the 2nd bit in 4 is a 0

It will also work with chars because they are also numbers in C,C++

Upvotes: 1

qdii
qdii

Reputation: 12983

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

Upvotes: 7

brut3f0rc3
brut3f0rc3

Reputation: 1183

That is very easy Lets say you need to access individual bits of an integer Create a mask like this int mask =1; now, anding your numberwith this mask gives the value set at the zeroth bit in order to access the bit set at ith position (indexes start from zero) , just and with (mask<

Upvotes: 1

Matt
Matt

Reputation: 7160

If you want access bit N:

Get: (INPUT >> N) & 1;

Set: INPUT |= 1 << N;

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

Toggle: INPUT ^= 1 << N;

Upvotes: 70

Related Questions