0

Lets say I have the following:

int x = 0;
string newX = "0x00A3B43C";

How can I set x to the newX string? I've tried converting it to an int32 but it throws System.FormatException, so that won't work.

Edit: This isn't really a duplicate, I shouldn't have to convert a hex to an int to define it as an int, right? Example

Niklas
  • 955
  • 15
  • 29
Justin G
  • 172
  • 3
  • 19
  • See [here](https://msdn.microsoft.com/en-us/library/bb311038.aspx), or [here](http://www.google.com); – Quantic Sep 29 '16 at 21:48
  • 1
    Possible duplicate of [How to parse hex values into a uint?](http://stackoverflow.com/questions/98559/how-to-parse-hex-values-into-a-uint) – Cᴏʀʏ Sep 29 '16 at 21:49
  • Duplicate of https://stackoverflow.com/questions/4279892/convert-a-string-containing-a-hexadecimal-value-starting-with-0x-to-an-integer – Stefano Balzarotti Sep 29 '16 at 21:52
  • @Justin The duplicate question, second answer, replace `uint` with `int` and it will work. Your screenshot isn't equivalent -- those hex values are not strings. – Cᴏʀʏ Sep 29 '16 at 21:54
  • I've seen that method and tried it, but it returns 10728508. I want to set x to the hex value while keeping it in it's hex form. – Justin G Sep 29 '16 at 22:00
  • @JustinG: Not sure I'm understanding. They are equivalent representations of the same number. Hex is just base 16 while the int is base 10. Perhaps with a little more context around your question it will become clearer. – Cᴏʀʏ Sep 29 '16 at 22:05

1 Answers1

1

You can parse the string fairly easily:

int x;
string newX = "0x00A3B43C";

if (int.TryParse(newX.Substring(2), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out x))
{
    Console.WriteLine("x = {0}", x); // 10728508
}

source

You do not need to convert hex notation to an int to assign it to an int, the compiler takes care of it for you. For example:

int y = 0x00A3B43C;
Console.WriteLine("y = {0}", y); // 10728508

In both cases, the console will output the value 10728508.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • 1
    If you wanted to convert the `int` value back to a hexadecimal string, you can use `string hex = y.ToString("X");` – Abion47 Sep 29 '16 at 22:20