How can I set all bits to '1' in a binary number of an unknown size?
-
03-07-2019 - |
Question
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.
Solution
~(x & 0)
x & 0 will always result in 0, and ~ will flip all the bits to 1s.
OTHER TIPS
Set it to 0, then flip all the bits to 1 with a bitwise-NOT.
You're going to find that in assembly language you have to know the size of a "passed in number". And in assembly language it really matters which machine the assembly language is for.
Given that information, you might be asking either
- How do I set an integer register to all 1 bits?
or
- How do I fill a region in memory with all 1 bits?
To fill a register with all 1 bits, on most machines the efficient way takes two instructions:
Clear the register, using either a special-purpose clear instruction, or load immediate 0, or xor the register with itself.
Take the bitwise complement of the register.
Filling memory with 1 bits then requires 1 or more store instructions...
You'll find a lot more bit-twiddling tips and tricks in Hank Warren's wonderful book Hacker's Delight.
Set x to 1
While x < number x = x * 2
Answer = number or x - 1.
The code assumes your input is called "number". It should work fine for positive values. Note for negative values which are twos complement the operation attempt makes no sense as the high bit will always be one.
Set it to -1
. This is usually represented by all bits being 1.
Use T(~T(0))
.
Where T
is the typename (if we are talking about C++.)
This prevents the unwanted promotion to int
if the type is smaller than int
.