2

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Ryan
  • 23
  • 3
  • Shouldn't use variable names like "var", it is a reserved keyword. – bnem Mar 20 '14 at 14:58
  • Did you try changing the type of `total` and `power` to `long`? – Sergey Kalinichenko Mar 20 '14 at 14:58
  • Take a look at these two posts: http://stackoverflow.com/questions/1139957/c-sharp-convert-integer-to-hex-and-back-again, http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c – bnem Mar 20 '14 at 15:06
  • @bnem I know I shouldn't do that, I was just trying a lot of stuff so I wasn't too concerned with names. Once I found something that works, I am going back to fix things like that. – Ryan Mar 20 '14 at 15:08
  • @dasblinkenlight Thank you! That worked perfectly. I can't believe I overlooked something that small. – Ryan Mar 20 '14 at 15:11

1 Answers1

0

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523