Bitwise - How can I check if a binary number contains another?

筅森魡賤 提交于 2020-07-20 07:53:43

问题


  A  = 110000000    -    384 Blue+Red
  B  = 011000010    -    194 Green+Black+Red

  A & B =   C  = 010000000    -    128 Red

How can I check if B contains all the bits in A and perhaps others? In the case above I would like to get "false".

I'm using XCode & objective-c but that shouldn't matter as far as I know


回答1:


B contains A if A & B (ie, the intersection) is equal to A:

(a & b) == a

Which is analogous to

a ⊆ b ↔ (a ∩ b) = a

from set theory.




回答2:


If you mean exactly the same bits, the test is A == B.

If you mean B must have all the bits that are set in A, and perhaps others, (A & B) == A.




回答3:


Use ex-nor

 In C ^ is ex-or operator and ~ is complement, to get ex-nor use ~(a^b)

if a and b are same then all bits will be 1 in ~(a^b)



来源:https://stackoverflow.com/questions/21257165/bitwise-how-can-i-check-if-a-binary-number-contains-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!