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

10,764

Solution 1

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

int.Parse (tmp, NumberStyles.HexNumber);

Solution 2

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));
    }

Solution 3

The radix is on Integer.valueOf(), not s.substring() in the java code you show there, so this would become:

ai[j] = Int32.Parse(s.Substring(j * 2, j * 2 + 2), 16);
Share:
10,764
Marcello Grechi Lins
Author by

Marcello Grechi Lins

Updated on June 04, 2022

Comments

  • Marcello Grechi Lins
    Marcello Grechi Lins almost 2 years

    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