Replace zero to one and opposite. Used for negative decimals to binary conversion. - CSharp System

CSharp examples for System:Hex

Description

Replace zero to one and opposite. Used for negative decimals to binary conversion.

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/*from   ww w  .j  a va2 s  .  c  o  m*/

public class Main{
        /// <summary>
        /// Replace zero to one and opposite. Used for negative decimals to binary conversion.
        /// </summary>
        private static string ReplacerZeroAndOnes(string input)
        {
            char[] replaced = input.ToCharArray();

            for (int i = 0; i < replaced.Length; i++)
            {
                if (replaced[i] == '0')
                {
                    replaced[i] = '1';
                }
                else
                {
                    replaced[i] = '0';
                }
            }

            // Define number of zeros and ones
            int digits = 0;

            if (input.Length > 16)
            {
                digits = 32 - input.Length;
            }
            else if (input.Length > 32)
            {
                digits = 64 - input.Length;
            }
            else
            {
                digits = 16 - input.Length;
            }

            return new string('1', digits) + new string(replaced);
        }
}

Related Tutorials