views:

591

answers:

6

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.

+16  A: 

~(x & 0)

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

Sean
WTF? Why do you even need x? ~0 is what that boils down to, your description even alludes to it ("will always result in 0, ...").
paxdiablo
@Pax: perhaps because the constant 0 could be of any numeric type. Including the x gives a context (and thus a size, or more importantly bit count), depending on the compiler.
Adam Robinson
Very nice trick for getting the proper type! +1.
R..
A: 

What do you mean "unknown size"? Is your function receiving an address that points to the location of some bigint?

Ben Collins
+2  A: 

Set it to -1. This is usually represented by all bits being 1.

sth
This is true of _signed_ integers in most implementations I've seen, but to be on the safe side I'd probably use the bitwise NOT method eg by Sean.
thomasrutter
+4  A: 

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

yjerem
A: 

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.

mP
That must be the performance wise optimal way
Viktor Sehr
+3  A: 

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:

  1. Clear the register, using either a special-purpose clear instruction, or load immediate 0, or xor the register with itself.

  2. 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.

Norman Ramsey