2 's complement for a givin string using XOR | PHP program to find 2 's complement using XOR. ; A flag used to find if a 1 bit is seen or not . ; xor operator is used to flip the ; bits after converting in to ASCII values ; if there is no 1 in the string so just add 1 in starting of string and return ; Driver code
< ? php function TwoscomplementbyXOR ( $ str ) { $ n = strlen ( $ str ) ; $ check_bit = 0 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { if ( $ str [ $ i ] == '0' && $ check_bit == 0 ) { continue ; } else { if ( $ check_bit == 1 ) $ str [ $ i ] = ( $ str [ $ i ] - '0' ) ^ 1 + '0' ; $ check_bit = 1 ; } } if ( $ check_bit == 0 ) return "1" + $ str ; else return $ str ; } $ str = "101" ; echo TwoscomplementbyXOR ( $ str ) ; ? >