Create string with ones and zeros. Limited to exact number of digits. - CSharp System

CSharp examples for System:Math Number

Description

Create string with ones and zeros. Limited to exact number of digits.

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/* www .  j av  a2  s. co m*/

public class Main{
        /// <summary>
        /// Create string with ones and zeros. Limited to exact number of digits.
        /// </summary>
        public static string DecToBinExact(long input)
        {
            bool negative = false;

            // If number is negative +1 and convert to positive and continue with conversion
            if (input < 0)
            {
                input += 1;
                input *= -1;
                negative = true;
            }
            StringBuilder sb = new StringBuilder();

            while (input != 0)
            {
                long remainder = input & 1;
                input /= 2;
                sb.Append(remainder);
            }

            // If number is negative reverse 1 to 0 and 0 to 1
            if (negative)
            {
                return ReplacerZeroAndOnes(Reverser(sb.ToString()));
            }
            else
            {
                return Reverser(sb.ToString());
            }
        }
}

Related Tutorials