Mil*_*lan 98 c c++ bit-manipulation
int temp = 0x5E; // in binary 0b1011110.
Run Code Online (Sandbox Code Playgroud)
有没有这种方法可以检查temp中的第3位是1还是0而没有位移和屏蔽.
只是想知道是否有一些内置功能,或者我自己不得不写一个.
mou*_*iel 154
在C中,如果要隐藏位操作,可以编写一个宏:
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
Run Code Online (Sandbox Code Playgroud)
并以这种方式使用它:
CHECK_BIT(temp, n - 1)
Run Code Online (Sandbox Code Playgroud)
在C++中,您可以使用std :: bitset.
Joa*_*lva 82
检查是否设置了位N(从0开始):
temp & (1 << N)
Run Code Online (Sandbox Code Playgroud)
没有内置功能.
use*_*714 24
如果它是C++,我会使用std :: bitset.简单.直截了当.没有机会犯愚蠢的错误.
typedef std::bitset<sizeof(int)> IntBits;
bool is_set = IntBits(value).test(position);
Run Code Online (Sandbox Code Playgroud)
或者这种愚蠢
template<unsigned int Exp>
struct pow_2 {
static const unsigned int value = 2 * pow_2<Exp-1>::value;
};
template<>
struct pow_2<0> {
static const unsigned int value = 1;
};
template<unsigned int Pos>
bool is_bit_set(unsigned int value)
{
return (value & pow_2<Pos>::value) != 0;
}
bool result = is_bit_set<2>(value);
Run Code Online (Sandbox Code Playgroud)
sho*_*r92 12
选择的答案实际上做错了什么.以下函数将返回位位置或0,具体取决于该位是否实际启用.这不是海报所要求的.
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
Run Code Online (Sandbox Code Playgroud)
这是海报最初寻找的内容.如果该位有效,则下面的函数将返回1或0,而不是位置.
#define CHECK_BIT(var,pos) (((var)>>(pos)) & 1)
Run Code Online (Sandbox Code Playgroud)
gim*_*mel 11
根据位域的这种描述,存在一种用于直接定义和访问字段的方法.此条目中的示例如下:
struct preferences {
unsigned int likes_ice_cream : 1;
unsigned int plays_golf : 1;
unsigned int watches_tv : 1;
unsigned int reads_books : 1;
};
struct preferences fred;
fred.likes_ice_cream = 1;
fred.plays_golf = 1;
fred.watches_tv = 1;
fred.reads_books = 0;
if (fred.likes_ice_cream == 1)
/* ... */
Run Code Online (Sandbox Code Playgroud)
此外,还有一个警告:
然而,结构中的位成员具有实际缺点.首先,内存中位的排序取决于体系结构,内存填充规则因编译器而异.此外,许多流行的编译器生成用于读写位成员的低效代码,并且由于大多数机器无法操作内存中的任意位组,因此存在与位域相关的严重线程安全问题(尤其是在多处理器系统上).但必须加载并存储整个单词.
Mr.*_*Ree 11
是的,我知道我没有"这样做".但我经常写:
/* Return type (8/16/32/64 int size) is specified by argument size. */
template<class TYPE> inline TYPE BIT(const TYPE & x)
{ return TYPE(1) << x; }
template<class TYPE> inline bool IsBitSet(const TYPE & x, const TYPE & y)
{ return 0 != (x & y); }
Run Code Online (Sandbox Code Playgroud)
例如:
IsBitSet( foo, BIT(3) | BIT(6) ); // Checks if Bit 3 OR 6 is set.
Run Code Online (Sandbox Code Playgroud)
除此之外,这种方法:
使用std :: bitset
#include <bitset>
#include <iostream>
int main()
{
int temp = 0x5E;
std::bitset<sizeof(int)*CHAR_BITS> bits(temp);
// 0 -> bit 1
// 2 -> bit 3
std::cout << bits[2] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
#define CHECK_BIT(var,pos) ((var>>pos) & 1)
Run Code Online (Sandbox Code Playgroud)
pos - 从 0 开始的位位置。
返回 0 或 1。
归档时间: |
|
查看次数: |
248115 次 |
最近记录: |