Consultor Eletrônico



Kbase P67951: Functions that Implement Bit Manipulation (BINARY AND OR)
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   10/16/2007
Status: Unverified

GOAL:

Functions that Implement Bit Manipulation (BINARY AND OR)

GOAL:

How to implement Binary and Or functions

FIX:

The following functions are implemented in the code shown below:
- Convert a signed integer into an unsigned integer
- Convert an unsigned integer into a signed integer
- Do a bitwise AND of two integers
- Do a bitwise OR of two integers

Step by step details:

FUNCTION IntToUnsignedInt RETURNS DECIMAL
(INPUT intOperand AS INTEGER):

DEFINE VARIABLE decUnsignedInt AS DECIMAL NO-UNDO.

ASSIGN decUnsignedInt = intOperand.

IF intOperand < 0 THEN
ASSIGN decUnsignedInt = EXP(2, 32) + decUnsignedInt.

RETURN decUnsignedInt.

END FUNCTION.


FUNCTION UnsignedIntToInt RETURNS INTEGER
(INPUT decOperand AS DECIMAL):

DEFINE VARIABLE intSignedInt AS INTEGER NO-UNDO.

IF decOperand < EXP(2, 31) THEN
ASSIGN intSignedInt = decOperand.
ELSE
ASSIGN intSignedInt = decOperand - EXP(2, 32).

RETURN intSignedInt.

END FUNCTION.


FUNCTION BinaryAnd RETURNS INTEGER
(INPUT intOperand1 AS INTEGER, INPUT intOperand2 AS INTEGER):

DEFINE VARIABLE decValue AS DECIMAL NO-UNDO INITIAL 0.
DEFINE VARIABLE decLoop AS DECIMAL NO-UNDO.
DEFINE VARIABLE decOperand1 AS DECIMAL NO-UNDO.
DEFINE VARIABLE decOperand2 AS DECIMAL NO-UNDO.

ASSIGN decLoop = EXP(2, 31)
decOperand1 = IntToUnsignedInt(intOperand1)
decOperand2 = IntToUnsignedInt(intOperand2).

DO WHILE decLoop > 0.5:
ASSIGN decValue = decValue + decLoop
WHEN decOperand1 >= decLoop AND decOperand2 >= decLoop
decOperand1 = decOperand1 - decLoop
WHEN decOperand1 >= decLoop
decOperand2 = decOperand2 - decLoop
WHEN decOperand2 >= decLoop
decLoop = decLoop / 2.
END.

RETURN UnsignedIntToInt(decValue).

END FUNCTION.


FUNCTION BinaryOr RETURNS INTEGER
(INPUT intOperand1 AS INTEGER, intOperand2 AS INTEGER):

DEFINE VARIABLE decValue AS DECIMAL NO-UNDO INITIAL 0.
DEFINE VARIABLE decLoop AS DECIMAL NO-UNDO.
DEFINE VARIABLE decOperand1 AS DECIMAL NO-UNDO.
DEFINE VARIABLE decOperand2 AS DECIMAL NO-UNDO.

ASSIGN decLoop = EXP(2, 31)
decOperand1 = IntToUnsignedInt(intOperand1)
decOperand2 = IntToUnsignedInt(intOperand2).

DO WHILE decLoop > 0.5:
ASSIGN decValue = decValue + decLoop
WHEN decOperand1 >= decLoop OR decOperand2 >= decLoop
decOperand1 = decOperand1 - decLoop
WHEN decOperand1 >= decLoop
decOperand2 = decOperand2 - decLoop
WHEN decOperand2 >= decLoop
decLoop = decLoop / 2.
END.

RETURN UnsignedIntToInt(decValue).

END FUNCTION.