Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c - How can I check my byte flag, verifying that a specific bit is at 1 or 0?

I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a function that can be used to test any desired bit:

bool is_bit_set(unsigned value, unsigned bitindex)
{
    return (value & (1 << bitindex)) != 0;
}

A bit of explanation:

The left shift operator (<<) is used to create a bit mask. (1 << 0) will be equal to 00000001, (1 << 1) will be equal to 00000010, (1 << 3) will be equal to 00001000, etc. So a shift of 0 tests the rightmost bit. A shift of 31 would be the leftmost bit of a 32-bit value.

The bitwise-and operator (&) gives a result where all the bits that are 1 on both sides are set. Examples: 1111 & 0001 = 0001; 1111 & 0010 == 0010; 0000 & 0001 = 0000. So, the expression (value & (1 << bitindex)) will return the bitmask if the associated bit is 1 in value, or will return 0 if the associated bit is 0.

Finally, we just check whether the result is non-zero. (This could actually be left out, but I like to make it explicit.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...