AkisC
AkisC

Reputation: 827

delphi to C++ builder conversion

I have source code in Delphi I follow this http://hscripts.com/tutorials/cpp/bitwise-operators.php for bitwise operators to convert it in C++ Builder, but the result is different

Source code in Delphi

procedure TForm1.Button1Click(Sender: TObject)
var
    tmp, dynamicINT : integer;
begin
    dynamicINT := 42080;
    tmp := ((dynamicINT shl 1) or (dynamicINT shr 31) and $7FFFFFFF);

    Edit1.Text := IntToHex(tmp, 4);
end;

Delphi result : 148C0 correct!

Source code in C++ Builder

void __fasctall TForm1::Button1Click(TObject *Sender)
{
    int tmp = 0;
    int dynamicINT = 42080;

    tmp = ((dynamicINT << 1) || (dynamicINT >> 31) && 0x7FFFFFFF);
    Edit1->Text = IntToHex(tmp, 4);
}

C++ Builder result : 0001 ???

What is wrong with conversion ?

I'm using C++ Builder 6 and Delphi 7

Upvotes: 4

Views: 1835

Answers (3)

Wolf
Wolf

Reputation: 10238

In addition to Mat's answer, it might help you for porting to know that in C/C++, as opposed to Delphi/Pascal, any bool value is interchangeable with all integral and numeric types. The following nonsense example will not cause any warning by the compiler:

bool a = 6 * 7.89;
int b = true & 128;
float f = a + !b; // which is 2

...and last but not least: You may use Delphi unit files unchanged in C++-Builder projects. just try to add one of them to your project (this way you can do the migration - if still needed - step by step).

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613003

You are using logical operators. You need to use bitwise operators, & and |. What's more the C++ code needlessly initializes and then overwrites the tmp variable. Your code should be:

int dynamicINT = 42080;
int tmp = ((dynamicINT << 1) | (dynamicINT >> 31) & 0x7FFFFFFF);

One thing to be careful about in the translation is what is meant by the shift operators when applied to signed types. I believe that there will be no problem with the code in the question since dynamicINT has a fixed value. But perhaps in the real code it can vary. In which case you may encounter implementation defined or undefined behaviour.

I suspect that you should be using untyped variables here. I'd have these variables as Cardinal in the Delphi code and unsigned int in the C++ code.

Upvotes: 2

Mat
Mat

Reputation: 206729

|| and && are logical operators in C++, not bitwise operators. They only return true/false. The corresponding binary operators are | and &.

Try:

tmp = ((dynamicINT << 1) | (dynamicINT >> 31) & 0x7FFFFFFF);

Upvotes: 8

Related Questions