How to read specific bits of an unsigned int

ε祈祈猫儿з 提交于 2019-12-02 05:57:03

问题


I have an uint8_t and I need to read/write to specific bits. How would I go about doing this. Specifically what I mean is that I need to write and then later read the first 7 bits for one value and the last bit for another value.

edit: forgot to specify, I will be setting these as big endian


回答1:


You're looking for bitmasking. Learning how to use C's bitwise operators: ~, |, &, ^ and so on will be of huge help, and I recommend you look them up.

Otherwise -- want to read off the least significant bit?

uint8_t i = 0x03;

uint8_t j = i & 1; // j is now 1, since i is odd (LSB set)

and set it?

uint8_t i = 0x02;
uint8_t j = 0x01;

i |= (j & 1); // get LSB only of j; i is now 0x03

Want to set the seven most significant bits of i to the seven most significant bits of j?

uint8_t j = 24; // or whatever value
uint8_t i = j & ~(1); // in other words, the inverse of 1, or all bits but 1 set

Want to read off these bits of i?

i & ~(1);

Want to read the Nth (indexing from zero, where 0 is the LSB) bit of i?

i & (1 << N);

and set it?

i |= (1 << N); // or-equals; no effect if bit is already set

These tricks will come in pretty handy as you learn C.



来源:https://stackoverflow.com/questions/19626652/how-to-read-specific-bits-of-an-unsigned-int

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