# addition at the left of number

0

How we can we do addition at the left FF instead 00? For example we have a = E8, we need a = 0xFFFFFFe8

`````` 0xFFE26C02 -> 0xFFE26C02
0x000000e8 -> 0xFFFFFFe8
0x100000e8 -> 0x100000e8
0x001000e8 -> 0xFF1000e8
``````

P.S. data type int32 or int64

c++
c

2

I guess your problem is how put the bits left to the leftmost '1' in the number?

Here is my solution:

Let's take the number 01001000( as num ) for example:

1. First, do ~num and you get 10110111.
2. Then plus 1, and the answer of (~num+1) is 10111000.
3. Do (~num+1) & (num), and you get 00001000.

So in the end, the result of the (~num+1) & num is to get the rightmost '1' in the num.

To get the left most one, do a loop, and the condition is:

``````while(num-(~num+1)&num)
``````

In the end, you will get the number 01000000.

So it'll be easy to locate the '0' right to the leftmost '1'.

Hope it will help.

2

You can use the following to convert all leading bytes of `0` to `FF`

``````int RevLeadingZeros(int number)
{
if((number & 0xFF000000)==0)
number |= 0xFF000000
else
return number;
if((number & 0x00FF0000)==0)
number |= 0x00FF0000
else
return number;
if((number & 0x0000FF00)==0)
number |= 0x0000FF00
else
return number;
if((number & 0x000000FF)==0)
number |= 0x000000FF
else
return number;
}
``````
1

Without direct calculation, you can just iterate each byte of your integer and replace the last consecutive `00` with `FF`.

You can also `OR` your integer with a mask which can easily be built with a first traversing of your integer memory.

User contributions licensed under CC BY-SA 3.0