Ask Your Question
0

How set and especially clear bits?

asked 2024-04-13 11:34:23 +0100

Andr gravatar image

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
mask = ~(1 << n)

but ~ means in sage 1/x

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

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2024-04-13 19:30:22 +0100

Max Alekseyev gravatar image

updated 2024-04-14 00:00:07 +0100

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)

See also this Q&A: https://ask.sagemath.org/question/23823/

edit flag offensive delete link more

Comments

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

John Palmieri gravatar imageJohn Palmieri ( 2024-04-13 19:37:40 +0100 )edit

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

Max Alekseyev gravatar imageMax Alekseyev ( 2024-04-13 22:10:40 +0100 )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.

John Palmieri gravatar imageJohn Palmieri ( 2024-04-13 22:48:18 +0100 )edit

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

Max Alekseyev gravatar imageMax Alekseyev ( 2024-04-13 23:57:18 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2024-04-13 11:34:23 +0100

Seen: 182 times

Last updated: Apr 14