Represent Int32 as a Binary String in C#

To represent an Int32 as a binary string in C#, use the Convert.ToString() method with base 2 as the second parameter. This method converts the integer's binary representation into a readable string format.

Int32 represents a 32-bit signed integer that can hold values from -2,147,483,648 to 2,147,483,647.

Syntax

Following is the syntax for converting an integer to binary string −

Convert.ToString(value, 2)

Parameters

  • value − The integer value to convert to binary representation

  • 2 − The base for binary number system

Return Value

Returns a string containing the binary representation of the integer value.

Using Convert.ToString() for Positive Numbers

Example

using System;

class Demo {
    static void Main() {
        int val = 30;
        Console.WriteLine("Integer: " + val);
        Console.WriteLine("Binary String: " + Convert.ToString(val, 2));
        
        int val2 = 255;
        Console.WriteLine("Integer: " + val2);
        Console.WriteLine("Binary String: " + Convert.ToString(val2, 2));
    }
}

The output of the above code is −

Integer: 30
Binary String: 11110
Integer: 255
Binary String: 11111111

Using Convert.ToString() for Negative Numbers

When converting negative integers, the method returns the two's complement binary representation −

Example

using System;

class Demo {
    static void Main() {
        int positiveVal = 10;
        int negativeVal = -10;
        
        Console.WriteLine("Positive Integer: " + positiveVal);
        Console.WriteLine("Binary: " + Convert.ToString(positiveVal, 2));
        
        Console.WriteLine("Negative Integer: " + negativeVal);
        Console.WriteLine("Binary: " + Convert.ToString(negativeVal, 2));
    }
}

The output of the above code is −

Positive Integer: 10
Binary: 1010
Negative Integer: -10
Binary: 11111111111111111111111111110110

Converting Multiple Values with Different Bases

Example

using System;

class Demo {
    static void Main() {
        int val = 42;
        
        Console.WriteLine("Original Integer: " + val);
        Console.WriteLine("Binary (base 2): " + Convert.ToString(val, 2));
        Console.WriteLine("Octal (base 8): " + Convert.ToString(val, 8));
        Console.WriteLine("Hexadecimal (base 16): " + Convert.ToString(val, 16));
    }
}

The output of the above code is −

Original Integer: 42
Binary (base 2): 101010
Octal (base 8): 52
Hexadecimal (base 16): 2a

Conclusion

The Convert.ToString() method with base 2 provides an easy way to convert Int32 values to their binary string representation. For negative numbers, it returns the two's complement binary form, making it useful for understanding how integers are stored in memory.

Updated on: 2026-03-17T07:04:35+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements