9

How would I convert a string that represents an integer like "4322566" to a hex string?

2
  • 1
    You want to take a string equal to "4322566" and generate "41F506", right? Commented Jun 2, 2010 at 23:14
  • Yeah that is what I want Commented Jun 2, 2010 at 23:25

5 Answers 5

11

string s = int.Parse("4322566").ToString("X");

Sign up to request clarification or add additional context in comments.

3 Comments

You may want to make this more fault-tollerant with TryParse
I get a overflow exception when attempting to convert 2309737967
2309737967 is above int.MaxValue (2147483647). Use long instead.
2
int temp = 0;
string hexOut = string.Empty;
if(int.TryParse(yourIntString, out temp))
{
    hexOut = temp.ToString("X");
}

To handle larger numbers per your comment, written as a method

public static string ConvertToHexString(string intText)
{
    long temp = 0; 
    string hexOut = string.Empty; 
    if(long.TryParse(intText, out temp))
    { 
        hexOut = temp.ToString("X"); 
    } 
    return hexOut;
}

2 Comments

I get a overflow exception when attempting to convert 2309737967
change the type of temp to long and use long.TryParse
1

Try .ToString("X").

Comments

1

or .ToString("x") if you prefer lowercase hex.

Comments

0

Try

int otherVar= int.Parse(hexstring ,
System.Globalization.NumberStyles.HexNumber);

1 Comment

int -> string, not string -> int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.