Skip to footer content
Iron Academy Logo
Learn C#
Learn C#

Other Categories

Storing and Displaying Binary Values in C#

Tim Corey
9m 20s

Binary is how computers actually store and process data, but C# defaults to base 10 for everything you see on screen. If you're working with bit flags, network protocols, hardware registers, or just trying to understand how numbers are represented at the machine level, you need to know how to get binary values into C# and how to display them in a readable format.

In his video "Storing and Displaying Binary Values in C#", Tim Corey covers lesson three in his binary series. He demonstrates how to store binary literals using the 0b prefix, how to convert integers to their binary string representation with Convert.ToString(), and how to pad the output with leading zeros for clean formatting. If you're following the binary series or working with low-level data in C#, this covers the practical mechanics.

Storing Binary Literals in C#

[0:00 - 1:50] The first question Tim addresses is straightforward: how do you put a binary number into a C# variable? The answer is the 0b prefix, which tells the compiler to interpret the digits as base 2 rather than the default base 10.

// Store binary 1001 (which is 9 in decimal)
int binaryValue = 0b1001;
// Store binary 1001 (which is 9 in decimal)
int binaryValue = 0b1001;

Without the prefix, 1001 would be interpreted as one thousand and one. With 0b, it's treated as four binary digits representing the decimal value 9. Leading zeros are optional. Writing 0b00001001 is identical to 0b1001, but the longer form can make the bit positions easier to read when you're working with specific bit widths.

The variable type is a standard int. You can also use uint (unsigned integer) if you don't need negative values, or long for 64-bit storage. The binary literal syntax works with any of the whole-number types.

Displaying Numbers in Binary

[1:50 - 3:48] Storing a binary value is one thing. Seeing it as binary on screen is another. When you print an int with Console.WriteLine, C# outputs the base 10 representation. For 0b1001, that means you see 9, not 1001.

To get the binary string representation, use Convert.ToString() with a base parameter:

int binaryValue = 0b1001;

// Convert to binary string (base 2)
string representation = Convert.ToString(binaryValue, 2);

Console.WriteLine($"Base 10: {binaryValue}");      // Output: 9
Console.WriteLine($"Base 2: {representation}");     // Output: 1001
int binaryValue = 0b1001;

// Convert to binary string (base 2)
string representation = Convert.ToString(binaryValue, 2);

Console.WriteLine($"Base 10: {binaryValue}");      // Output: 9
Console.WriteLine($"Base 2: {representation}");     // Output: 1001

The second argument to Convert.ToString() specifies the output base. The supported values are 2 (binary), 8 (octal), 10 (decimal), and 16 (hexadecimal). Tim demonstrates base 2, but the same method handles all four.

Padding with Leading Zeros

[3:48 - 5:24] The raw output of Convert.ToString(binaryValue, 2) omits leading zeros. For 0b1001, the result is the string "1001", not "00001001". When you're working with bytes (8 bits), 16-bit values, or 32-bit registers, seeing the full width with leading zeros makes the bit positions immediately clear.

The fix is PadLeft():

// Pad to 8 characters (one byte) with leading zeros
string padded = Convert.ToString(binaryValue, 2).PadLeft(8, '0');

Console.WriteLine(padded);  // Output: 00001001
// Pad to 8 characters (one byte) with leading zeros
string padded = Convert.ToString(binaryValue, 2).PadLeft(8, '0');

Console.WriteLine(padded);  // Output: 00001001

PadLeft(8, '0') ensures the output is at least 8 characters long, filling any missing positions on the left with the character '0'. Tim notes the detail that the second argument is a char (single quotes), not a string. It's the character zero, not the number zero, because PadLeft builds a string from individual characters.

For a 16-bit representation, change 8 to 16. For a full 32-bit integer, use 32. The padding width should match the bit width you're reasoning about.

Converting Any Integer to Binary

[5:24 - 7:28] Tim makes a point that's easy to overlook: you don't have to store a value as a binary literal to see its binary representation. Any integer can be converted to binary output using the same Convert.ToString() approach:

// A regular base 10 integer
int decimalValue = 12;

// Convert to padded binary string
string binary = Convert.ToString(decimalValue, 2).PadLeft(8, '0');

Console.WriteLine($"Decimal: {decimalValue}");  // Output: 12
Console.WriteLine($"Binary: {binary}");          // Output: 00001100
// A regular base 10 integer
int decimalValue = 12;

// Convert to padded binary string
string binary = Convert.ToString(decimalValue, 2).PadLeft(8, '0');

Console.WriteLine($"Decimal: {decimalValue}");  // Output: 12
Console.WriteLine($"Binary: {binary}");          // Output: 00001100

The 0b prefix is for when you already have a binary value and want to enter it in binary form. For regular integers, Convert.ToString() handles the conversion. Both paths produce the same result for the same underlying value.

How C# Stores Integers in Memory

[7:28 - 9:20] Tim closes with a detail about how C# stores integers internally. An int in C# is an alias for System.Int32, a 32-bit signed integer. That means every int occupies 32 bits in memory, regardless of how small the value is. Storing 0b1001 (the number 9) uses the same 32 bits as storing 0b01111111111111111111111111111111 (over two billion).

// What's actually stored in memory for binaryValue = 0b1001
// 00000000 00000000 00000000 00001001
string fullRepresentation = Convert.ToString(binaryValue, 2).PadLeft(32, '0');
Console.WriteLine(fullRepresentation);
// What's actually stored in memory for binaryValue = 0b1001
// 00000000 00000000 00000000 00001001
string fullRepresentation = Convert.ToString(binaryValue, 2).PadLeft(32, '0');
Console.WriteLine(fullRepresentation);

This connects to why choosing the right type size matters. A long (Int64) uses 64 bits, doubling the memory footprint. For most applications, int (32 bits) covers the range you need. But if you're working in memory-constrained environments or processing millions of values, the difference between byte (8 bits), short (16 bits), int (32 bits), and long (64 bits) becomes significant.

Wrapping Up: The Complete Pattern

[9:07 - 9:15] The full pattern for working with binary in C# is concise. Store values using the 0b prefix when you have binary input. Display them using Convert.ToString(value, 2) for raw output. Add .PadLeft(width, '0') when you need fixed-width formatting. And remember that the underlying storage is always a standard integer type, with the bit width determined by whether you choose byte, short, int, or long.

Conclusion

[9:15 - 9:20] To sum it up: binary literals use the 0b prefix, Convert.ToString(value, 2) produces the binary string, and PadLeft() adds leading zeros for fixed-width display. The value is stored in a regular integer type under the hood, and an int always occupies 32 bits regardless of the magnitude of the number.

These building blocks show up in the next lessons in the series, where the binary values need to be properly formatted for bitwise operations.

Example Tip: When debugging bitwise operations, pad your binary output to the full width of your type (8 for byte, 16 for short, 32 for int). Seeing all the bit positions at once makes shift and mask operations far easier to trace. A helper method like string ToBinary(int val) => Convert.ToString(val, 2).PadLeft(32, '0'); saves repeated typing.

Watch full video on his YouTube Channel and gain more insights on understanding binary in C#.

Hero Worlddot related to Storing and Displaying Binary Values in C#
Hero Affiliate related to Storing and Displaying Binary Values in C#

Earn More by Sharing What You Love

Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me