iphone - comparing two numbers, getting the different bits in them and filling up a 16bit register, objective-C -
this may bit confusing. have 2 numbers, say
x = 56 = 00111000
y = 50 = 00110010
can see there total of 4 different bits between them. need take bits , fill part of 8 bit register. , in same way take 2 numbers ( there 4 bits different in them ) fill remaining part of 8 bit register. know how using objective-c ?
i don't know objective-c, wrote in c , tested it. hope don't mind:
unsigned int diffbits(unsigned int x, unsigned int y) { unsigned int xor_xy = x^y; unsigned int result = 0; unsigned int count = 0; while (xor_xy) { if ( xor_xy & 0x01) { result |= ((x & (1 << count)) >> count); result <<= 1; result |= ((y & (1 << count)) >> count); result <<= 1; } ++count; xor_xy >>= 1; } // undo last left shift of 'result' in while-loop. result >>= 1; return result; } the logic is: x ^ y (x xor y) - gives bit locations in numbers x , y different. test x bit value of x ^ y , push result. repeat y , push result. right shift x ^ y 1. repeat until x ^ y != 0.
Comments
Post a Comment