Wednesday, July 07, 2010

binary expansion in C# - converting BigInteger to binary form

This source code will do the job.
Add appropriate controls and fire the number: 174050332293622031404857552280219410364023488927386650641
and you'll get:
01110001100100101011100101011111111111001000110110100111100001100011000100000001000111101101011010110010010011001101110101010111001111111001011101111010000100011110011110010100100000010001
with a bunch of more noughts in front.
What a happy day. :)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Numerics;

namespace binaryexpansion
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
BigInteger t = BigInteger.Parse(inputnr.Text);
selResult.Text = calcBinary(t);

//the line below would work if t was an integer - so nice and easy, but no dice with BigIntegers
//string t2 = Convert.ToString(t, 2);

}


private string calcBinary(BigInteger tee) {

BigInteger t = tee;
//4 times the length because it takes about 3 times the number of digits to write a number i binary form
int len = 4*(inputnr.Text).Length;

string fullnum= " ";
for (int i = len; i >= 0; i--)
{
int inum;

BigInteger num = (t >> i)&1;
if(num == 1){
//ugly but easy
inum = 1;}
else if(num == 0){
inum = 0;}
else{
inum=666;
}
fullnum = fullnum + Convert.ToString(inum);

}
return fullnum;

}
}
}

No comments: