Convert a decimal to the binary format
//GNU General Public License version 2 (GPLv2)
//http://cbasetest.codeplex.com/license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SDFL.Helper
{
public class StrHelper
{
/// <summary>
/// Convert a decimal to the binary format.
/// like:
/// stra = Convert.ToString(4, 2).PadLeft(8, '0');
/// //stra=00000100
/// </summary>
/// <param name="DecimalNum"></param>
/// <returns></returns>
public static string ToBinary(Int64 decimalNum)
{
Int64 binaryHolder;
char[] binaryArray;
string binaryResult = "";
// fix issue#5943: StrHelper.ToBinary(0) result "", it should be 0
if (decimalNum == 0)
{
return "0";
}
// end fix issue#5943
while (decimalNum > 0)
{
binaryHolder = decimalNum % 2;
binaryResult += binaryHolder;
decimalNum = decimalNum / 2;
}
// rever the binaryResult, e.g. we get 1101111, then revert to 1111011, this is the final result
binaryArray = binaryResult.ToCharArray();
Array.Reverse(binaryArray);
binaryResult = new string(binaryArray);
return binaryResult;
}
}
}
Related examples in the same category