I have a string of eight 1s and 0s with spaces in between, something like "1 0 0 1 1 0 1 0", that I want converted in to an int. Is there a simple way to do this? I feel like some kind of linq parsing would do it, but I don't even know what to do with the characters once I find them.
Robert Harvey
181k48 gold badges349 silver badges515 bronze badges
asked Jan 10, 2013 at 17:55
2 Answers 2
You don't need any LINQ.
Convert.ToInt*()
takes an optional fromBase
parameter, which must be 2, 8, 10, or 16.
Convert.ToInt32("1 0 0 1 1 0 1 0".Replace(" ", ""), 2)
answered Jan 10, 2013 at 17:56
1 Comment
MLavine
Well that makes this a very simple problem then hah. Thanks so much!
An alternative to @SLaks's answer (but only for parsing Hex) is
Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
There's no equivalent for binary, though, so his is a better general-purpose answer.
answered Jan 10, 2013 at 18:00
1 Comment
Tilak
I was mistaken. Removed earlier comment.
lang-cs
1 0 0 1 1 0 1 0
should be parsed as two, four bit values:1001
and1010
. Then converted to hex. Correct?