Print a number in binary format.

S

Sin Jeong-hun

It looked like that I can print a number in hexadecimal format with
Console.Write, but I couldn't find how to print in binary format. I
mean 000...0001 for 1, 000...0010 for 2 and so on.

I wrote a dirty code, and it seemed to be working, but it looks like
quite inefficient. Is there any .NET built in method or a better way?

Below is the code I wrote:
class Program
{
static void Main(string[] args)
{
PrintInBinary(1);
PrintInBinary(1<<2);
}
static void PrintInBinary(int num)
{
byte[] bytes = BitConverter.GetBytes(num);
for (int count = bytes.Length - 1; count >= 0; count--)
{
for (int position = 7; position >= 0; position--)
PrintBitAt(bytes[count], position);
Console.Write(" ");
}
Console.WriteLine();
}
static void PrintBitAt(byte b, int position)
{
if(position>7)
return;
byte a=(byte)Math.Pow(2,position);
if ((b & a) == a)
Console.Write("1");
else
Console.Write("0");
}
}
 
K

Kerem Gümrükcü

Hi Sin Jeong-hun,

i think thats what you are looking for:


int SomeNumber = 12345;
string NumberBinaryString = Convert.ToString(SomeNumber, 2); //radix 2
MessageBox.Show(NumberBinaryString);


Regards

Kerem

--
 
M

Michael B. Trausch

int SomeNumber = 12345;
string NumberBinaryString = Convert.ToString(SomeNumber, 2); //radix 2
MessageBox.Show(NumberBinaryString);

Here is a full demo of a way to use that... it probably could be more
efficient, but it combines the built-in ability to convert it with some
custom code to format it for human consumption (see below for example
run):

============= BEGIN CODE
// Public Domain
//
// Example for converting numbers to binary and formatting them in
// standard format for display.

using System;
using System.Text;

public class ProgramEntry {
public static int Main(string[] args) {
if(args.Length == 0) {
Console.WriteLine("Provide a number on the command line.");
Console.WriteLine("i.e., \"radix2.exe 30\"");
return(1);
}

System.Int64 SomeNumber;

try {
SomeNumber = System.Int64.Parse(args[0]);
} catch(System.FormatException) {
Console.WriteLine("Invalid parameter.\n");

Console.WriteLine("Provide a number on the command line.");
Console.WriteLine("i.e., \"radix2.exe 30\"");
return(2);
} catch(System.OverflowException) {
Console.WriteLine("Parameter provided ({0}) is too big.",
args[0]);
return(3);
}

string NumberAsBinary = ConvertToBinary(SomeNumber);

Console.WriteLine("Original: {0:#,###}\nAltered: {1}\n",
SomeNumber, NumberAsBinary);
return(0);
}

/*
* Format a string containing a binary number do display in groups of
* 4.
*/
public static string FormatBinary(string binNum) {
if(binNum.Length % 4 != 0) {
throw new ArgumentException("BUG: Invalid parameter length");
}

StringBuilder sb = new StringBuilder();
char[] binNumAsArray = binNum.ToCharArray();

for(int i = 0; i < binNumAsArray.Length; i++) {
if((i % 4 == 0) && (i != 0)) {
sb.Append(" ");
}

sb.Append(binNumAsArray);
}

return(sb.ToString());
}

/*
* Convert the supplied integer to base 2 (binary) and format it
* as is customary.
*/
public static string ConvertToBinary(System.Int64 num) {
string originalConvertedValue = Convert.ToString(num, 2);

int paddingRequired = 4 - (originalConvertedValue.Length % 4);
if(paddingRequired == 4) paddingRequired = 0;

if(paddingRequired == 0) {
return(FormatBinary(originalConvertedValue));
} else {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < paddingRequired; i++) sb.Append("0");
sb.Append(originalConvertedValue);

return(FormatBinary(sb.ToString()));
}
}
}
============= END CODE

And the example run:

============= BEGIN OUTPUT
radix2.exe 13727
Original: 13,727
Altered: 0011 0101 1001 1111

radix2.exe 21919
Original: 21,919
Altered: 0101 0101 1001 1111

radix2.exe 8559
Original: 8,559
Altered: 0010 0001 0110 1111

radix2.exe 827
Original: 827
Altered: 0011 0011 1011

radix2.exe 5978
Original: 5,978
Altered: 0001 0111 0101 1010
============= END OUTPUT

HTH,
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top