Question

I am attempting to manually convert numbers between decimal and hexadecimal. I have it working for positive numbers and converting a negative decimal to 'negative' hexadecimal but I can't convert it from 'negative' hexadecimal to negative decimal.

Here is the code I am attempting to work with:

private string HexToDecimal(char[] toConvert)
    {
        if (negativeValue)
        {
            negativeValue = false;

            long var = Convert.ToInt64(HexToDecimal(ResultLabel.Text.ToCharArray()));

            long valueToHex = var - (long)Math.Pow(16, 15);

            return ResultLabel.Text = valueToHex.ToString();
        }
        else
        {
            double total = 0;
            //Convert hex to decimal

            HexOrDecimalLabel.Text = "Decimal";

            //TODO: create int array from indivial int
            char[] charArray = toConvert;
            long[] numberArray = HexSwitchFunction(charArray);

            //TODO: reverse array
            Array.Reverse(numberArray);

            //loop array, times value by 16^i++, adding to total. This is the method   used to convert hex to decimal
            double power = 0;
            foreach (int i in numberArray)
            {
                total += (i * (Math.Pow(16, power)));
                power++;
            }

            //set the result label to total

            isHex = false;
            AllowHexButtons();

            return ResultLabel.Text = total.ToString();
        }
    }

For instance, I can turn - 10 into FFFFFFFFFFFFFFF6, but when i attempt to turn that into decimal, I get 1.15292150460685E+18, which I can't do any equations with.

Does anyone know of a way around this?

Was it helpful?

Solution

This is because double uses a different representation for negative numbers. Changing the type of total and power from double to long will fix the problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top