如何阅读一个unsigned int的特定位 [英] How to read specific bits of an unsigned int
问题描述
我有一个uint8_t有,我需要读/写特定位。我怎么会去这样做。具体是什么我的意思是,我需要写,再后来读了前7位的一个值和另一个值的最后一位。
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
推荐答案
您正在寻找的 bitmasking 的。学习如何用C的位运算符:〜
, |
,&安培;
, ^
等将是巨大的帮助,我建议你看看他们。
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)
和设置呢?
uint8_t i = 0x02;
uint8_t j = 0x01;
i |= (j & 1); // get LSB only of j; i is now 0x03
希望我的七个最显著位设置到j的七个最显著位?
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);
要(从零,其中0表示LSB索引)我的位?
Want to read the Nth (indexing from zero, where 0 is the LSB) bit of i?
i & (1 << N);
和设置呢?
i |= (1 << N); // or-equals; no effect if bit is already set
这些技巧会在pretty方便你学习C
These tricks will come in pretty handy as you learn C.
这篇关于如何阅读一个unsigned int的特定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!