Mohammad Reza Rezwani
Mohammad Reza Rezwani

Reputation: 331

String of binary to integer

I have a string which contains of 0 and 1. I wanna know if there is any method in c# to convert this in Uint32 . I know how to do that without any method but just I wanna know if there is any method does that automatically?

Upvotes: 2

Views: 244

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98830

You can use Convert.ToInt32 Method (String, Int32) overload.

Converts the string representation of a number in a specified base to an equivalent 32-bit signed integer.

Like;

uint i = Convert.ToUInt32("010101", 2); //21

Here a DEMO.

(010101)2 = 20 * 1 + 21 * 0 + 22 * 1 + 23 * 0 + 24 * 1 + 25 * 0 = 21

Upvotes: 2

JaredPar
JaredPar

Reputation: 755179

Try using the Convert.ToUInt32 method. There is an overload which allows you to specify the number base you are converting from

uint x = Convert.ToUInt32("01010", 2);

Here is the MSDN page for that member

Upvotes: 7

I4V
I4V

Reputation: 35363

string s = "0101";
uint i = Convert.ToUInt32(s, 2); //<--5

Upvotes: 4

Related Questions