user2087438
user2087438

Reputation:

Incorrect conversion from hex to int in C#

What can be the reason for the problem? My method returns incorrect int values. When I give it hex value of AB or DC or something similar it returns int = 0 but when I give it a hex = 22 it returns me int = 22. (though int should be 34 in this case).

public int StatusBit(int Xx, int Rr)  {
        int Number;
        int.TryParse(GetX(Xx,Rr), out Number);
            return Number;
    }

I tried to use Number = Convert.ToInt32(GetX(Xx,Rr)); but it gives same result but null instead of 0 for anything that includes letters.

Upvotes: 2

Views: 1830

Answers (4)

Monjen72
Monjen72

Reputation: 11

here is my solution;

kTemp = int.Parse(xcc, System.Globalization.NumberStyles.HexNumber);

above kTemp is an integer, and xcc is a string. xcc can be anything like; FE, 10BA, FE0912... that is to say; xcc is a string of hex characters in any length. beware; I dont get the 0x prefix with my hex strings.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502066

Use NumberStyles.HexNumber:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        string text = "22";
        int value;
        int.TryParse(text, NumberStyles.HexNumber, 
                     CultureInfo.InvariantCulture, out value);
        Console.WriteLine(value); // Prints 34
    }
}

Do you really want to silently return 0 if the value can't be parsed, by the way? If not, use the return value of int.TryParse to determine whether the parsing succeeded or not. (That's the reason it's returning 0 for "AB" in your original code.)

Upvotes: 4

thumbmunkeys
thumbmunkeys

Reputation: 20764

int.TryParse parses a base 10 integer.

Use Convert.ToUInt32(hex, 16) instead

Upvotes: 1

Joey
Joey

Reputation: 354694

Use Convert.ToInt32(string, int) instead. That way you can give a base the number should be interpreted in. E.g.

return Convert.ToInt32(GetX(Xx, Rr), 16);

(You also don't check the return value of TryParse which would give a hint that the parse failed.)

If you expect both decimal and hexadecimal numbers you need to branch according to how the number looks and use either base 10 or base 16. E.g. if your hexadeximal numbers always start with 0x you could use something along the following lines:

string temp = GetX(Xx, Rr);
return Convert.ToInt32(temp, temp.StartsWith("0x") ? 16 : 10);

But that would depend on how (if at all) you would distinguish the two. If everything is hexadecimal then there is no such need, of course.

Upvotes: 4

Related Questions