Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Convert Delphi to c#

Posted on 2011-03-23
10
Medium Priority
?
1,167 Views
Last Modified: 2012-05-11
I am having problems converting the following from Delphi to C#:

const
  cKey1 = 57287;
  cKey2 = 34321;

    function Decrypt(CONST s:  STRING; Key:  WORD):  STRING;
    var
      b:   BYTE;
      i:   INTEGER;
    begin
        b := 0;
        RESULT := '';
        FOR i := 1 TO LENGTH(s) DIV 2 DO
        begin
          try
            b :=  StrToInt('$' + COPY(s, 2*i-1, 2));
          except
            ON EConvertError DO b := 0
          end;
          RESULT := RESULT + CHAR( b XOR (key SHR 8) );
          key := (b + key) * Ckey1 + Ckey2
        end
    end;
0
Comment
Question by:markusr13
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
10 Comments
 

Author Comment

by:markusr13
ID: 35201810
use this as a test: "9DD6678ACD84FC0211DBCA543EE1F5"
0
 

Author Comment

by:markusr13
ID: 35201819
probably should note that they key = 51474
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35202419
I get "TheSkyIs" in C# - conversion from one to the other doesn't seem terribly difficult, the Delphi syntax seems relatively obvious (I've never even seen Delphi before, and was able to make some sense out of it).

Did you give it a try?  Was there something in particular you were stuck at?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 24

Accepted Solution

by:
jimyX earned 252 total points
ID: 35202469
I am from Delphi zone and i do not know much about C#. The following is my trying:
public const int cKey1 = 57287;
public const int cKey2 = 34321;

public STRING Decrypt(string Name s, ushort Key)
{
    Byte b = 0;
    int i;
    string result = "";
    for (int i = 1; i <= s.Length / 2; i++)
    {
    try 
    {
      b = int.Parse(s.Substring(2*i-2, 2), NumberStyles.AllowHexSpecifier);
    }
    catch
    {
      b = 0;
    }
      result += (char)( b ^ (key >> 8) );
      key = (b + key) * Ckey1 + Ckey2;
    }
    return result;
}

Open in new window

0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 248 total points
ID: 35202484
Well, I had already done the work, I was just trying not to give it away for free, just in case this was a homework assignment or something. ;)

static string Decrypt(string encryptedString, ushort Key)
{
	ushort cKey1 = 57287, cKey2 = 34321;
	StringBuilder returnValue = new StringBuilder();

	for (int i = 0; i < encryptedString.Length / 2; i +=2)
	{
		byte b;
		try
		{
			b = Byte.Parse(encryptedString.Substring(i, 2), NumberStyles.HexNumber);
		}
		catch
		{
			b = 0;
		}

		returnValue.Append((char)(b ^ (Key >> 8)));

		Key = (ushort)((b + Key) * cKey1 + cKey2);
	}

	return returnValue.ToString();
}

Open in new window

0
 
LVL 24

Expert Comment

by:jimyX
ID: 35202608
@ tgerbert
Sorry mate, did not mean to spoil it.

Side comment ;-)
>   "Delphi syntax seems relatively obvious"
That's sure thing.

>   "I've never even seen Delphi before"
Oh man, Delphi is the best. Try using it, you will be amazed.

Cheers
0
 

Author Comment

by:markusr13
ID: 35203599
Man, this looks pretty much looks like what I did...

What was getting me was "key := (b + key) * Ckey1 + Ckey2"

A word is only 65,535 but this calculation goes beyond that. I didn't dig into Delphi to see exactly how it was handling it. C# (ushort) doesn't handle it as gracefully....I thought.

I will test more tomorrow. jimyX version works on my test string tgerbert falls a little short (I will see why tgerbert's only returned me 8 characters).

Points come tomorrow.

(Delphi is great, c# is Delphi on steroids as it was written even better by the person (Anders) that wrote Delphi) but i still miss the bookmarks which must have been patented by Borland. VS has something similar but can't be numbered and they cross units.

-Markus

0
 

Author Comment

by:markusr13
ID: 35203641
working solution (thanks to both of you). I don't know what I was smoking but I should have solved it myself. I had to have been doing something dumb on this line: Key = (ushort)((b + Key) * cKey1 + cKey2);

public string Decrypt(string s, ushort Key)
{
    Byte b = 0;

    string result = "";
    for (int i = 1; i <= s.Length / 2; i++)
    {
    try
    {
      b = (byte)int.Parse(s.Substring(2*i-2, 2), NumberStyles.AllowHexSpecifier);
    }
    catch
    {
      b = 0;
    }
    result += (char)(b ^ (Key >> 8));
    Key = (ushort)((b + Key) * cKey1 + cKey2);
    }
    return result;
}
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35203718
I made a typo (copied the "/ 2" from your Delphi code, realized I didn't need it, but forgot to take it out).
Couple notes...

1. Use meaningful variable names, particularly for method parameters, e.g. "encryptedString" instead of "s"

2. Instead of this goofy construct ".Substring(2*i-2, 2)", you can initialize the for loop's iterator, i, to 0, make it's condition that i is less than the string's length, and increment it by two each iteration, instead of 1, you can write ".Substring(i, 2)" - which changes the "for" loop from "for (int i = 1; i <= s.Length / 2; i++)" to "for (int i = 0; i < s.Length; i += 2)"

3. The byte "b" is of no use to me outside of the for loop, so I deliberately declared it inside the loop to limit it's scope.

4. Don't concatenate strings in loops like this using syntax such as "result += someOtherString" - since strings in .Net are immutable (meaning once created they can't be changed), you're actually creating new strings everytime you do that. That's what the StringBuilder is intended for.

static public string Decrypt(string encryptedString, ushort Key)
{
	ushort cKey1 = 57287, cKey2 = 34321;
	StringBuilder returnValue = new StringBuilder();

	for (int i = 0; i < encryptedString.Length; i += 2)
	{
		byte b;
		try
		{
			b = Byte.Parse(encryptedString.Substring(i, 2), NumberStyles.HexNumber);
		}
		catch
		{
			b = 0;
		}

		returnValue.Append((char)(b ^ (Key >> 8)));

		Key = (ushort)((b + Key) * cKey1 + cKey2);
	}

	return returnValue.ToString();
}

Open in new window


Funny how, even though I'd never seen Delphi code before, I could deduce that "key SHR 8" means shift-right by 8 bits - but if I had never seen C# before, the equivelant statement "key >> 8" would be almost meaningless. I still prefer C# though. ;)

Bookmarks (if they're what I think they are) would be a feature of the text editor Borland ships with their product, not the language.  There are a number of free text editors available that handle things like syntax highlighting for C# (and other languages) that might do what you want - there's nothing that says you have to use Visual Studio to write C#.
0
 
LVL 25

Expert Comment

by:epasquier
ID: 35205018
@tgerbert :  the Delphi syntax seems relatively obvious

Indeed it is. And that sample was an easy one, you would be amazed how readable it is for complex things (objects). Compared to C syntax (and all derived Java, C++, C#) Delphi is just pure vanilla
And to say that the framework is also simple AND effective is an understatement. If you like .Net, you have to LOVE Delphi if you give it a try

I would like to know why you still prefer C#, as you said quite correctly that Delphi is so readable that any good programmer with no specific knowledge of it can understand it. Maybe we can convince you otherwise :o)

> c# is Delphi on steroids
I wouldn't say C# (.Net in fact) is better than Delphi. Let's say it is Java redesigned for MS world in Delphi spirit but keeping C-style syntax. a kind of hydra with multiple heads if you ask me, a powerful one for sure. But it couldn't be compared with any native language, as far as performance is concerned.

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

597 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question