且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用纯粹的ABAP位操作实现两个整数相加

更新时间:2022-09-05 23:13:18

Recently I came across this very funny picture and I would like to share with you.


This picture shows totally five different approaches to implement “a + b”, and how your brain reacts when you read these code


From this picture we know that for most guys, they will be crazy when they read the source code of the last solution as the code is really difficult to understand compared with all other four solutions.

使用纯粹的ABAP位操作实现两个整数相加

The idea of the last solution is to achieve the add operation via bitwise operation &, | and ^. See detail of these three operations via wikipedia.

You might be interested with how ABAP can play around with these bitwise operation from two of my blogs:


Bitwise operation ( OR, AND, XOR ) on ABAP Integer

An interview question: Compare two integers without +,-,*,/ or > and <

Back to the last solution to implement a + b using bitwise operation, the code actually conveys the idea how the Adder is designed in electronics. See detail design in Wikipedia.

使用纯粹的ABAP位操作实现两个整数相加

The idea is to use & to determine whether there is a carry about the add result of current bit, and use | to store the add result of current bit.


For example, how 2 + 3 = 5 works via bitwise operation:

使用纯粹的ABAP位操作实现两个整数相加

And here below is my implementation using ABAP( Only integers which >= 0 are supported ).

使用纯粹的ABAP位操作实现两个整数相加

使用纯粹的ABAP位操作实现两个整数相加

This solution might not make too much sense from business perspective but it at least help me refresh what I have learned in my university.