.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Convert a decimal to the binary format

Posted By:SanthoshNathan       Posted Date: November 01, 2010    Points: 15    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  

Convert a decimal to the binary format
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SDFL.Helper
{
    public class StrHelper
    {
        /// 
        ///         Convert a decimal to the binary format.
        ///         like: 
        ///         stra = Convert.ToString(4, 2).PadLeft(8, '0');
        ///         //stra=00000100
        /// 

        /// 
        /// 
        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;
        }    

    }
}


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend