Mocke
Mocke

Reputation: 39

How to convert hex in format 00-00 to double?

I am getting values in a format like this 00-C6 (Hex). It complains when I try to convert it to double (format execption). What to do?

    public void check()
    {
        double low;
        double high;
        percentageCalculator(4095, 5, out low, out high);
        Dictionary[] A_1 = {Max_1, Min_1};

        for (int i = 0; i < A_1.Length; i++)
        {
            if ((Convert.ToDouble(A_1[i].CurrentValue) <= low) || ((Convert.ToDouble(A_1[i].CurrentValue) >= high))
            {
                Fault++;
            }
        }
    }

Upvotes: 1

Views: 863

Answers (2)

Ian
Ian

Reputation: 30813

Assuming the Hex 00-C6 string represents Integer value (because if it represents floating-point value like float or double, it must consists of 4-byte or 8-byte), then one way to process it is to split the Hex string:

string hexString = "00-C6";
string[] hexes = hexString.Split('-');

Then you process each element in the hexes like this:

int hex0 = Convert.ToInt32(hexes[0], 16);
int hex1 = Convert.ToInt32(hexes[1], 16);

If the hex is little endian, then your double value would be:

double d = hex0 << 8 + hex1;

And if it is big endtion, your double will be:

double d = hex1 << 8 + hex0;

The key here is to know that you can convert hex string representation to Int by using Convert.ToInt32 with second argument as 16.

You can combine all the steps above into one liner if you feel like. Here I purposely break them down for the sake of presentation clarity.

Upvotes: 2

nabuchodonossor
nabuchodonossor

Reputation: 2060

Take a look at this piece of code:

        string hexnumber = "00-c6";
        double doubleValue = (double)Convert.ToInt32(hexnumber.Replace("-", ""), 16);

Upvotes: 1

Related Questions