1

I can't seem to properly convert the following from VB.NET to C#--

iKeyChar = Asc(mid(g_Key, i, 1))
iStringChar = Asc(mid(strCryptThis,i,1))

Here's my converted C# code, which doesn't seem to output equivalent values--

iKeyChar = Convert.ToInt32(g_Key.Substring(i, 1));
iStringChar = Convert.ToInt32(strCryptThis.Substring(i, 1));

Any help is greatly appreciated!

ianpoley
  • 552
  • 2
  • 10
  • 20

4 Answers4

8

That's because Mid is one based while Substring is zero based. Try it this way:

iKeyChar = (int)Convert.ToChar(g_Key.Substring(i-1, 1));
iStringChar = (int)Convert.ToChar(strCryptThis.Substring(i-1, 1));
System Down
  • 6,192
  • 1
  • 30
  • 34
  • 1
    Also Asc [returns](http://msdn.microsoft.com/en-us/library/zew1e4wc(v=vs.71).aspx) an ANSI code but Convert.ToInt32 tries to convert the string to a number, e.g. "1" is 1, "2' is 2 etc. – MarkJ Oct 26 '12 at 21:37
  • That kind of depends on if and what they have their Option Base set to doesn't it? – Daniel Graham Oct 26 '12 at 21:39
  • 1
    @MarkJ - Yeah I've heard of that. Do you know of an exact analog to Asc in C# (other than importing Microsoft.VisualBasic)? – System Down Oct 26 '12 at 21:42
  • @DanielGraham - "Option Base"? I thought VB.NET didn't have that? – System Down Oct 26 '12 at 21:43
  • @MarkJ - Apparently casting it to `char` *then* casting it to `int` should do the trick. – System Down Oct 26 '12 at 22:28
1

It's the ASCII bit that's the problem. See here: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/13fec271-9a97-4b71-ab28-4911ff3ecca0 and here: What's the equivalent of VB's Asc() and Chr() functions in C#?

Community
  • 1
  • 1
David Osborne
  • 6,436
  • 1
  • 21
  • 35
0

Try this:

        int iKeyChar = Convert.ToChar(g_key.Substring(i, 1));
        int iStringChar = Convert.ToChar(strCryptThis.Substring(i, 1));
Daniel Graham
  • 399
  • 3
  • 13
0

Simply access the desired char by its index withing the string and cast it to int:

iKeyChar = (int)g_Key[i - 1];
iStringChar = (int)strCryptThis[i - 1];

Note that index of the string characters is zero based (as System Down said in his post).

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188