The correct solution would be to do
var bit = Math.Log(a ^ b, 2);
Although of course this leaves open the question of what happens if for any reason more than one bit is different.
You could use
var bit = (int)Math.Log(a ^ b, 2);
to get you the index of the highest different bit, if more than one differ.
Warning: For correctness, any such function should also check that the two arguments a
and b
are actually different before trying to provide a result. Otherwise you 'll get either a meaningless result or an outright exception. This is true of all the solutions presented here, including this one.