如何检查c中的位设置? [英] How to check how a bit is set in c?

查看:60
本文介绍了如何检查c中的位设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

How to check a bit in a variable whether it is set or not using C language

推荐答案

与CP的答案相关:



Related to CP''s answer:

#define bit_set(val, bit_no) (((val) >> (bit_no)) & 1)





这个数字位从(n-1)到0从高值位到低位,即a short 最低位(值1)是位号0,最高位(值32768)是数字15.



This numbers bits from (n-1) to 0 from the high value bits to the low, i.e. in a short the lowest bit (value 1) is bit number 0, and the highest (value 32768) is number 15.


(例如)使用 shift 和按位,例如

(For instance) With a shift and a bitwise and, e.g.
// check if bit 5 is set
if ( (val >> 5) & 1)
{
  // bit is set
}
else
{
  // bit unset
}


上面列出的解决方案适用于非结构化测试。如果您从头开始设计系统,并且您知道算法的数据结构需要检查位,那么您应该调查位字段的使用。



http://en.wikipedia.org/wiki/Bit_field [ ^ ]
The solutions listed above are good for unstructured testing. If you are designing a system from scratch and you know that the data structure for your algorithm is going to need to check bits then you should investigate the use of bit fields.

http://en.wikipedia.org/wiki/Bit_field[^]


这篇关于如何检查c中的位设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆