basic bit flip algorithm

27,869

Solution 1

Can be done with the bitwise XOR operator, which is ^ in Python.

Example:

a = 0xF0101010
b = 0xFFFFFFFF
print(bin(a))
print(bin(b))
print(bin(a ^ b))

0b11110000000100000001000000010000
0b11111111111111111111111111111111
0b1111111011111110111111101111

Solution 2

foreach x in input:
    x_flipped = ~x & 0xffffffff
    print "bits flipped in unsigned 32-bit", bin(x_flipped)

Explained: - (~x) flips all bits ~ (& 0xffffffff) converts 2's complement into unsigned int.

Share:
27,869
sanster9292
Author by

sanster9292

Graduated with a pre-med degree from college. Now doing Machine Learning

Updated on January 15, 2020

Comments

  • sanster9292
    sanster9292 over 4 years

    So i am new to programming. Took a basic course in python so i know the basics and i am trying to practice a lot more and i am attempting this question and i dont know where to start.

    You will be given a list of 32-bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). Input Format

    The first line of the input contains the list size T. T lines follow each line having an integer from the list.

    Constraints

    1 ≤ T ≤ 100

    Output Format

    Output one line per element from the list with the requested result.

    Sample Input

    3 2147483647 1 0

    Sample Output

    2147483648 4294967294 4294967295

    Explanation

    Take 1 for example, as unsigned 32-bits is 00000000000000000000000000000001 and doing the flipping we get 11111111111111111111111111111110 which in turn is 4294967294

  • sanster9292
    sanster9292 over 9 years
    is this the way that you were suggesting? def flipflop(bits): the_bit = raw_input("") bit_flipped = ~(the_bit) & 0xffffffff print bin(bit_flipped) I am getting a traceback error that says that bit_flipped is not defined