Conversion between a binary string and integer in C#
This post will discuss how to convert a binary string in C# to an integer (and vice-versa).
1. Using Convert.ToInt32() method
The standard solution to convert the specified value to a 32-bit signed integer is using the built-in method Convert.ToInt32(). The specified value can be a binary string, unsigned integer, floating-point number, etc.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string binary = "1100100"; int i = Convert.ToInt32(binary, 2); Console.WriteLine(i); // 100 } } |
To convert the specified value to a 16-bit signed integer, use the Convert.ToInt16 method. Similarly, to convert the specified value to a 64-bit signed integer, use the Convert.ToInt64 method. The Convert class also offers the unsigned integer counterparts like ToUInt16(), ToUInt32(), and ToUInt64() method.
2. Using Convert.ToString() method
To do the opposite, i.e., convert an integer to a binary string, you can use the Convert.ToString() method. It converts the specified integer value to its equivalent string representation in the specified base. This method is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int value = 100; string binary = Convert.ToString(value, 2); Console.WriteLine(binary); // 1100100 } } |
That’s all about conversion between a binary string and integer in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)