Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set all bits to '1' in a binary number of an unknown size?

I'm trying to write a function in assembly (but lets assume language agnostic for the question).

How can I use bitwise operators to set all bits of a passed in number to 1?

I know that I can use the bitwise "or" with a mask with the bits I wish to set, but I don't know how to construct a mask based off some a binary number of N size.


2 Answers

~(x & 0)

x & 0 will always result in 0, and ~ will flip all the bits to 1s.

like image 103
Sean Avatar answered Sep 13 '25 08:09

Sean


Set it to 0, then flip all the bits to 1 with a bitwise-NOT.

like image 39
Paige Ruten Avatar answered Sep 13 '25 09:09

Paige Ruten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!