Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Represent Int64 as a Binary string in C#
To represent Int64 as a binary string in C#, use the Convert.ToString() method with base 2 as the second parameter. Int64 represents a 64-bit signed integer that can hold values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Syntax
Following is the syntax for converting Int64 to binary string −
Convert.ToString(longValue, 2)
Parameters
-
longValue − The
Int64value to convert - 2 − The base for binary representation
Return Value
Returns a string representation of the Int64 value in binary format (base 2).
Using Convert.ToString() for Binary Conversion
Example
using System;
class Demo {
static void Main() {
long val = 753458;
Console.WriteLine("Long: " + val);
Console.WriteLine("Binary String: " + Convert.ToString(val, 2));
}
}
The output of the above code is −
Long: 753458 Binary String: 10110111111100110010
Converting Multiple Int64 Values
Example
using System;
class Program {
static void Main() {
long[] values = {0, 1, 15, 255, 1024, 753458, 9223372036854775807};
Console.WriteLine("Int64 to Binary Conversion:");
Console.WriteLine("---------------------------");
foreach(long val in values) {
string binary = Convert.ToString(val, 2);
Console.WriteLine($"Decimal: {val,20} | Binary: {binary}");
}
}
}
The output of the above code is −
Int64 to Binary Conversion: --------------------------- Decimal: 0 | Binary: 0 Decimal: 1 | Binary: 1 Decimal: 15 | Binary: 1111 Decimal: 255 | Binary: 11111111 Decimal: 1024 | Binary: 10000000000 Decimal: 753458 | Binary: 10110111111100110010 Decimal: 9223372036854775807 | Binary: 111111111111111111111111111111111111111111111111111111111111111
Handling Negative Int64 Values
Example
using System;
class Program {
static void Main() {
long positiveVal = 753458;
long negativeVal = -753458;
Console.WriteLine("Positive Value: " + positiveVal);
Console.WriteLine("Binary: " + Convert.ToString(positiveVal, 2));
Console.WriteLine();
Console.WriteLine("Negative Value: " + negativeVal);
Console.WriteLine("Binary: " + Convert.ToString(negativeVal, 2));
}
}
The output of the above code is −
Positive Value: 753458 Binary: 10110111111100110010 Negative Value: -753458 Binary: 1111111111111111111111111110100100000010000001101110
Conclusion
The Convert.ToString() method with base 2 effectively converts Int64 values to their binary string representation. This method handles both positive and negative values, with negative values represented using two's complement notation in the binary output.
