# How set and especially clear bits?

I try

n.set_bit(7)


No set_bit, clear_bit methods for n. Next I try clear by bit mask

x = 14
n = 1


but ~ means in sage 1/x

Is good solution using subtraction? Fore example 2^256 - 1 - 2^32

edit retag close merge delete

Sort by ยป oldest newest most voted

If I guessed the meaning of your "n.set_bit(7)" correctly, then it can be achieved via Python's bitwise operator | as

n |= 1<<7


You can find more details on bitwise operators at https://realpython.com/python-bitwise...

To make ~ work as in Python, convert the argument to int first:

mask = ~int(1 << n)


or as suggested in the comments:

mask = ~(int(1) << n)


or simply

mask = ~(1r << n)


more

I think it suffices to just convert 1 to an int: ~(int(1) << n).

( 2024-04-13 19:37:40 +0200 )edit

Or just ~(1r << n) (corrected).

( 2024-04-13 22:10:40 +0200 )edit

Or ~(1r << n): no need for int if you're using r. Of course any of these it may overflow if n is too large.

( 2024-04-13 22:48:18 +0200 )edit

Yes, this is what I meant, just forgot to remove int.

( 2024-04-13 23:57:18 +0200 )edit