Convert an Integer to Binary in C#
This post will discuss how to convert an integer to a 32-bit binary string in C#.
There are several ways to convert an integer to binary format in C#:
1. Using Convert.ToString() method
The recommended approach is to use the built-in method Convert.ToString for converting a signed integer value to its equivalent string representation in a specified base. The base must be one of 2, 8, 10, or 16; otherwise, an ArgumentException is thrown. This method is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int val = -1; string binary = Convert.ToString(val, 2); Console.WriteLine(binary); } } /* Output: 11111111111111111111111111111111 */ |
This method can be extended to convert from any base to any base in C# where the base must be 2, 8, 10, or 16.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { string val = "100"; int from = 10; int to = 2; string binary = Convert.ToString(Convert.ToInt32(val, from), to); Console.WriteLine(binary); } } /* Output: 1100100 */ |
2. Custom routine
We can also write our own custom routine to convert an unsigned integer to its equivalent string representation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public class Example { public static string ToBinary(int x) { char[] buff = new char[32]; for (int i = 31; i >= 0 ; i--) { int mask = 1 << i; buff[31 - i] = (x & mask) != 0 ? '1' : '0'; } return new string(buff); } public static void Main() { int val = 1000; // unsigned integer string binary = ToBinary(val); Console.WriteLine(binary); } } /* Output: 00000000000000000000001111101000 */ |
That’s all about converting an integer to Binary 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 :)