Bit Shifts with ABAP

I am trying to port some Java code that requires arithmetic and logical bit shifts to ABAP. As far as I know, ABAP only supports bitwise NOT, AND, OR, and XOR operations.

Does anyone know a different way to implement these shifts using ABAP? Is there a way to get the same result as shifts using only NOT, AND, OR, and XOR operations?

+2
source share
2 answers

Edit: Updated code can now be found here: github gist

+2
source

Disclaimer: I am not specifically familiar with ABAP, so this answer is given at a more general level.

Assuming that what you said is true (ABAP does not support shifts, which I somewhat doubt), you can use multiplication and division.

Logical Left Shift (LSHL)

It can be expressed in terms of multiplication:

x LSHL n = x * 2^n 

For example, given x=9, n=2 :

 9 LSHL 2 = 9 * 2^2 = 36 

Logical Right Shift (LSHR)

It can be expressed using (truncation) division:

 x LSHR n = x / 2^n 

Given x=9, n=2 :

 9 LSHR 2 = 9 / 2^2 = 2.25 -> 2 (truncation) 

Arithmetic left shift (here: "ASHL")

If you want to perform arithmetic shifts (save sign), we need to further refine the expressions to save the sign bit.

Assuming we know that we are dealing with a 32-bit signed integer, where the most significant bit is used to represent the sign:

 x ASHL n = ((x AND (2^31-1)) * 2^n) + (x AND 2^31) 

Example: changing Integer.MAX_VALUE from left to one in Java

As an example of how this works, let's consider that we want to shift Java Integer.MAX_VALUE left by one. A logical left shift can be represented as *2 . Consider the following program:

 int maxval = (int)(Integer.MAX_VALUE); System.out.println("max value : 0" + Integer.toBinaryString(maxval)); System.out.println("sign bit : " + Integer.toBinaryString(maxval+1)); System.out.println("max val<<1: " + Integer.toBinaryString(maxval<<1)); System.out.println("max val*2 : " + Integer.toBinaryString(maxval*2)); 

Program Output:

 max value : 01111111111111111111111111111111 (2147483647) sign bit : 10000000000000000000000000000000 (-2147483648) max val<<1: 11111111111111111111111111111110 (-2) max val*2 : 11111111111111111111111111111110 (-2) 

The result is negative due to the fact that the most significant bit in integer is used to represent the sign. We get the exact number -2 due to the way negative numbers represent Java (for details see, for example, http://www.javabeat.net/qna/30-negative-numbers-and-binary-representation-in/ )

+3
source

All Articles