Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string representation of binary number to int in C#

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.

like image 337
MLavine Avatar asked Jan 10 '13 17:01

MLavine


2 Answers

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)
like image 109
SLaks Avatar answered Sep 25 '22 01:09

SLaks


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.

like image 23
Bobson Avatar answered Sep 26 '22 01:09

Bobson