Take the 2-minute tour ×

I receive a string from an external interface which holds an INT32 value. This value represents "-100" - a signed int - and thus, looking like this string "4294967196". If it would look like "-100" I could use Int32.TryParse() to cast it to a signed value. But in my case it interprets the values as is and tells me that the value is too big (>2.147.483.647). Any workaround to get this working? How to tell the parser that the leading 1 is not a number?

Edit: Sorry for being inaccurate. The value I receive is a string that looks like this "4294967196". It represents an Uint32 with the value -100. If the interface would return a string holding "-100" it would be possible to just use Int32.TryParse(). That's what I was trying to express.

share|improve this question
long.TryParse? –  asawyer Apr 24 '12 at 19:49
What do you mean by "leading 1"? –  usr Apr 24 '12 at 19:49
What's wrong with (int) (uint.Parse("4294967196"))? –  Skiminok Apr 24 '12 at 19:50
Am I missing something? You get a string that is "-100", and it's equivalent to "4294967196"? I don't get what "If it would look like -100 I could use Int32.TryParse() to cast it to a signed value" means since "-100" is "-100" to me. And "leading 1 is not a number?" - what does that mean? –  birryree Apr 24 '12 at 19:50
@skiminok You should post that as an answer –  AHM Apr 24 '12 at 19:53

1 Answer 1

up vote 10 down vote accepted

Use uint.TryParse() and cast the result to int.

string s = "4294967196";
uint ux;
int x = 0;
if (uint.TryParse(s, out ux))
    x = (int)ux;
// x = -100
share|improve this answer
awesome thx. but there's a typo, it should be (s, out ux). –  wanderameise Apr 24 '12 at 19:53
Ah, yes, @Habib fixed it first. –  Kendall Frey Apr 24 '12 at 19:56
I don't seem to have the ability to add comments (too new?) but Habib's answer does have a slight problem that I can see. A UInt could parse correctly to a value an explicit Int32 cast would fail on. The line: x = (int)ux; would throw an exception if the value of the string exceeded 2,147,483,647. Not sure if that is a problem or not, but some small coding changes to handle that may be in order. –  CosmicFreddy Apr 24 '12 at 20:23
It is worth noting that this would not work in a checked context, because it would throw an OverflowException. –  David Anderson - DCOM Apr 24 '12 at 21:22

Your Answer


