Binary to signed decimal - CSharp System

CSharp examples for System:Math Number

Description

Binary to signed decimal

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/*  w  ww  .j  a v  a 2s  .  c om*/

public class Main{
        /// <summary>
        /// Binary to signed decimal
        /// </summary>
        public static long BinToSDec(string input)
        {
            bool negative = false;

            if (input[0] == '1')
            {
                negative = true;
            }

            long result = 0;
            byte[] binValue = new byte[input.Length];
            int pow = input.Length - 1;

            // Fill array with 0 and 1
            for (int i = 0; i < input.Length; i++)
            {
                binValue[i] = byte.Parse(input[i].ToString());
            }

            for (int pos = 0; pos < binValue.Length; pos++)
            {
                if (pos == 0 && negative)
                {
                    result += binValue[pos] * (Numbers.NumberToPower(2, pow) * (-1));
                }
                else
                {
                    result += binValue[pos] * Numbers.NumberToPower(2, pow);
                }

                pow--;
            }

            return result;
        }
}

Related Tutorials