How to find the number of msb bits common between two binary numbers

124 Views Asked by At

Im trying to find the number of bits common between two binary numbers starting from MSB -> LSB. For example, I'm taking a set of binary numbers of 4 bits each i.e., 0 -> 15.

  • I'm trying to find the number of common bits between 8(1000) and 12(1100). Starting from msb we see that there is only one common bit. hence answer should be (1)
  • 0(0000) and 15(1111) = 0
  • 10(1010) and 11(1011) = 3
  • 6(0110) and 8(1000) = 0

Is there a formula to do this? Or should it be brute forced by checking each bit when writing code?