Create string with zero or ones. Detect automatically number and choose 8, 16, 32, 64 digits. - CSharp System

CSharp examples for System:String Algorithm

Description

Create string with zero or ones. Detect automatically number and choose 8, 16, 32, 64 digits.

Demo Code


using System.Text;
using System.Collections.Generic;
using System;//from ww w.  jav a2  s  .co  m

public class Main{
        /// <summary>
        /// Create string with zero or ones. Detect automatically number and choose 8, 16, 32, 64 digits.
        /// </summary>
        public static string DecToBin(long input)
        {
            // Define number of zeros and ones
            int digits = 0;

            if (input > sbyte.MaxValue || input < sbyte.MinValue)
            {
                digits = 15;
            }
            else if (input > short.MaxValue || input < short.MinValue)
            {
                digits = 31;
            }
            else if (input > int.MaxValue || input < int.MinValue)
            {
                digits = 63;
            }
            else
            {
                digits = 7;
            }

            string inputToBin = string.Empty;

            for (int bitPosition = digits; bitPosition >= 0; bitPosition--)
            {
                long bitValue = (input >> bitPosition) & 1;
                inputToBin += bitValue;
            }

            return inputToBin;
        }
}

Related Tutorials