Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer.ValueOf method equivalence in C# With Radix Parameter

Tags:

java

c#

migration

My task is to migrate this Java code to a C# version, but I'm having trouble with the ValueOf method, since I can't seem to find a equivalent version for C# (because of the Radix parameter used on Java, 16 in this case).

public String decrypt_string(String s) 
{
  String s1 = "";
  int i = s.length() / 2;
  int[] ai = new int[i];

  for (int j = 0; j < i; j++) 
  {
    // This is the "problematic" line \/
    ai[j] = Integer.valueOf(s.substring(j * 2, j * 2 + 2), 16).intValue();
  }

  int[] ai1 = decrypt_block(ai, i);

  for (int k = 0; k < i; k++) 
  {
    if (ai1[k] != 0)
      s1 = s1 + (char)ai1[k];
  }

return s1;

}

Here is my try, but it failed:

public String decrypt_string(String s)
    {
        String s1 = "";
        int i = s.Length / 2;
        int[] ai = new int[i];

        for (int j = 0; j < i; j++)
        {
            int startIndex = j * 2;
            string tmp = s.Substring(startIndex, 2);
            ai[j] = Int32.Parse (tmp); 
        }

        int[] ai1 = decrypt_block(ai, i);

        for (int k = 0; k < i; k++)
        {
            if (ai1[k] != 0)
                s1 = s1 + (char)ai1[k];
        }
        return s1;
    }

Thanks in advance

like image 554
Marcello Grechi Lins Avatar asked Apr 20 '12 14:04

Marcello Grechi Lins


2 Answers

If you are trying to parse a hexadecimal (base-16) number, use this:

int.Parse (tmp, NumberStyles.HexNumber);
like image 102
agent-j Avatar answered Sep 28 '22 23:09

agent-j


You need to convert a string to an integer, given that the string is in a specific base.

int i = Convert.ToInt32(str, 16);
int j = Convert.ToInt32("A", 16); // 10

So:

    for (int j = 0; j < i; j++)
    {
        int startIndex = j * 2;
        ai[j] = Convert.ToInt32(s.Substring(startIndex, 2));
    }
like image 40
SimpleVar Avatar answered Sep 28 '22 22:09

SimpleVar