TtT23
TtT23

Reputation: 7030

How to compare two hexadecimal numbers

What is the best way to compare two hexadecimal numbers (that is a string)? For instance,

string a = "3F";
string b = "32";

if (a > b)
   MessageBox.Show("a is greater");

Should work. (Assuming > has been properly overloaded).

Upvotes: 3

Views: 14568

Answers (4)

Rozwel
Rozwel

Reputation: 2020

Here is a fairly robust implementation of hendrik’s suggestion. There are a number of ways it could be optimized if your input strings have known attributes, but it should be able to compare valid hex strings of any size and/or with mixed formats.

public int HexStringCompare(string value1, string value2)
{
    string InvalidHexExp = @"[^\dabcdef]";
    string HexPaddingExp = @"^(0x)?0*";
    //Remove whitespace, "0x" prefix if present, and leading zeros.  
    //Also make all characters lower case.
    string Value1 = Regex.Replace(value1.Trim().ToLower(), HexPaddingExp, "");
    string Value2 = Regex.Replace(value2.Trim().ToLower(), HexPaddingExp, "");

    //validate that values contain only hex characters
    if (Regex.IsMatch(Value1, InvalidHexExp))
    {
        throw new ArgumentOutOfRangeException("Value1 is not a hex string");
    }
    if (Regex.IsMatch(Value2, InvalidHexExp))
    {
        throw new ArgumentOutOfRangeException("Value2 is not a hex string");
    }

    int Result = Value1.Length.CompareTo(Value2.Length);
    if (Result == 0)
    {
        Result = Value1.CompareTo(Value2);
    }

    return Result;
}

Using this to answer the OP's question:

if (HexStringCompare(a, b) > 0)
   MessageBox.Show("a is greater");

Upvotes: 1

hendrik
hendrik

Reputation: 2042

There is also a simple algo based on String comparisson: Assumed your numbers have a unique format: always lower case or higher case letters. Leading 0x or not, no leading zeros. Then you can do like this: If number a has more digits than number b: a > b

If the number of digits is equal you could use String.Compare.

This algo has the advantage it is not limited to 32 or 64 bits.

Upvotes: 2

kprobst
kprobst

Reputation: 16651

You can always convert them to ints and compare them that way:

int a = int.Parse("3E", System.Globalization.NumberStyles.HexNumber);
int b = int.Parse("32", System.Globalization.NumberStyles.HexNumber);

if (a > b)
    MessageBox.Show("a is greater");

Seems safer :)

Upvotes: 9

Russell Borogove
Russell Borogove

Reputation: 19037

Convert them to integers and compare the integers.

Upvotes: 3

Related Questions