C++如何知道数字是否以某种位模式结尾

标签 c++ bit

我想知道数字是否以某些预定义的位模式结尾。

例如 我想知道一个数字 N 是否以 B 结尾

其中,N是任意数字 B也是任意数

例如

if N = 01011100 
  B = 100 then this C++ function should return 1 here in this case 1

if N = 01011100
  B = 101 then this function should return 0

:)

最佳答案

对于第一种情况:

unsigned n = 0x5C;
unsigned m = 0x7; // "mask"
unsigned b = 0x4;
if ((n & m)==b) {
  ...do something...
}

这是它的工作原理:

01011100  n
00000111  m
00000100  n & m  (bitand operator)
00000100  b

关于C++如何知道数字是否以某种位模式结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5513451/

相关文章:

c++ - 如何在 Xcode 项目中包含 C++ Actor Framework?

c - 访问字符中的位?

java - C++到Java代码转换疑惑

javascript - 使用 % 和获取奇数/偶数的最低有效位之间的区别

Java位比较,bitset?

c++ - bitset 未设置正确的值

c++ - boost::unique_lock,多次读取正在减慢编写器的速度

c++ - Visual Studio 2013,错误 MSB8020 : The build tools for Visual Studio 2010 cannot be found

c++ - 如果构造函数发生异常,如何释放动态内存?

c++ - C++编程基础问题