magicbottle

now an anji main and ๆฐดๆœˆใฎ้‹ใณ-ing away

  • they/them
Bench 1RM58 kg
Squat 1RM85 kg
Deadlift 1RM105 kg
ClimbingNewb
ProgrammingC, Rust, Python
CSS Crimes?Sometimes
Gender?Sometimes
Affection?Affectionate
DiscordMagicBottle#9930

Floor

How do you compute โŒŠ๐‘ฅ+๐‘ฆ2โŒ‹ without overflow in ๐‘ฅ+๐‘ฆ ?

We can decompose the addition into two parts, an addition with carries ignored (XOR) and one with the carries, shifted into place:

  • ๐‘ฅ+๐‘ฆ=(๐‘ฅโŠ•๐‘ฆ)+((๐‘ฅย &ย ๐‘ฆ)โ‰ช1)

We shift right by one on both sides, cancelling out the shift left:

  • (๐‘ฅ+๐‘ฆ)โ‰ซ1=((๐‘ฅโŠ•๐‘ฆ)โ‰ซ1)+(๐‘ฅย &ย ๐‘ฆ)

Ceiling

If you want to calculate โŒˆ๐‘ฅ+๐‘ฆ2โŒ‰ however, we can use a different, more exciting identity for addition that uses subtraction:


  • ๐‘ฅ+๐‘ฆ=((๐‘ฅย |ย ๐‘ฆ)โ‰ช1)โˆ’(๐‘ฅโŠ•๐‘ฆ)

And then after shifting right by one on both sides we are left with:

  • (๐‘ฅ+๐‘ฆ)โ‰ซ1=(๐‘ฅย |ย ๐‘ฆ)โˆ’((๐‘ฅโŠ•๐‘ฆ)โ‰ซ1)

This goes to the ceiling because we are flooring the part we are subtracting via the right shift.

Uh, where did that new subtraction based identity come from?

Working backwards towards another well known identity, if we spell out the left shift with addition we get:

  • ๐‘ฅ+๐‘ฆ=(๐‘ฅย |ย ๐‘ฆ)+(๐‘ฅย |ย ๐‘ฆ)โˆ’(๐‘ฅโŠ•๐‘ฆ)

Then using the following identity for exclusive or:

  • ๐‘ฅโŠ•๐‘ฆ=(๐‘ฅย |ย ๐‘ฆ)โˆ’(๐‘ฅย &ย ๐‘ฆ)

We get the following, being careful with the sign:

  • ๐‘ฅ+๐‘ฆ=(๐‘ฅย |ย ๐‘ฆ)+(๐‘ฅย |ย ๐‘ฆ)โˆ’(๐‘ฅย |ย ๐‘ฆ)+(๐‘ฅย &๐‘ฆ)

Or:

  • ๐‘ฅ+๐‘ฆ=(๐‘ฅย |ย ๐‘ฆ)+(๐‘ฅย &ย ๐‘ฆ)

Source

Hacker's Delight, Dietz, and HAKMEM. Using pommicket's LaTeX tool, which I wanted an excuse to try.

this is my first post


You must log in to comment.