[英]Check if a binary number has a '0' or a '1' at a specific position
I'd like to check if a binary number has a '0' or a '1' at a specific position. 我想检查二进制数在特定位置是否有'0'或'1'。
example: 例:
if the binary number is: 101000100 如果二进制数是:101000100
checking at position 6 should result in '1'. 检查位置6应该导致'1'。
etc... 等等...
I'm coding in C, so obviously I could use sprintf / scanf and the likes, but I guess there must be something better (read: more time efficient / easier)! 我用C编码,显然我可以使用sprintf / scanf等等,但我想必须有更好的东西(阅读:更节省时间/更容易)!
What would be a good mechanism to do this? 这样做的好机制是什么?
This will filter out the bit you're looking for: 这将过滤掉您正在寻找的位:
number & (1 << position)
If you really need a 1 or 0 response, you can use this to make it a boolean value: 如果你真的需要1或0响应,你可以使用它来使它成为一个布尔值:
!!(number & (1 << position))
Or even better (thanks Vadim K. ): 甚至更好(感谢Vadim K. ):
(number >> position) & 1
此表达式求值为您要查找的位的值, 0
或1
:
(number >> position) & 1
Warning: This code is not Standards-compliant. 警告:此代码不符合标准。 Bjarne Stroustrup says , and he oughta' know, that, "Obviously, it's illegal to write one member and then read another..." Nevertheless I leave this code up for educational purposes...
Bjarne Stroustrup说 ,并且他应该知道,“显然,写一个成员然后读另一个成员是违法的......”不过我把这些代码留给教育目的......
Here's an alternative that is useful when, say, reading a proprietary binary protocol off of a socket: 这里有一个替代方案,比如从套接字读取专有二进制协议时很有用:
#include <cstdlib>
union Value
{
struct
{
unsigned char a_ : 1;
unsigned char b_ : 1;
unsigned char c_ : 1;
unsigned char d_ : 1;
unsigned char e_ : 1;
unsigned char f_ : 1;
unsigned char g_ : 1;
unsigned char h_ : 1;
} bits_;
unsigned char charVal_;
};
int main()
{
unsigned char someValue = static_cast<unsigned char>(0x42);
Value val;
val.charVal_ = someValue;
bool isBitDSet = val.bits_.d_;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.