Access individual bits in a char c++

荒凉一梦 提交于 2019-12-28 10:46:03

问题


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


回答1:


If you want access bit N:

Get: (INPUT >> N) & 1;

Set: INPUT |= 1 << N;

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

Toggle: INPUT ^= 1 << N;




回答2:


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




回答3:


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<

来源:https://stackoverflow.com/questions/9531214/access-individual-bits-in-a-char-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!