Home > Software design >  Trying to convert from hexadecimal to decimal and binary but shows an error if i input letter after
Trying to convert from hexadecimal to decimal and binary but shows an error if i input letter after

Time:01-03

I created this code in c# to convert a hexadecimal number entered by the user to decimal and binary which the code does but I want the code to run so that if the user enters a letter that is not between a-f, a message box shows up with a message telling the user their input is invalid but instead of doing this, the code gives me an error. Can anyone help me out?

    bool valid = false;
    string hexadecimalnum = HexadecimalTxt.Text;

Checking if the number inputed by the user is in between 0-9 and a-f (lowercase or uppercase)

    if(Regex.IsMatch(hexadecimalnum, "\[^-9A-F\] $") || Regex.IsMatch(hexadecimalnum, "\[^-9a-     f\] $"))
    {
        // if the hex value is in between 0-9 and a-f then the condition is true  
        valid = true;
    }

since the condition is true convert the hex number to binary and decimal

    if(valid)
    {

        DecimalTxt.Text = Convert.ToInt32(hexadecimalnum, 16).ToString();
        int temp = Convert.ToInt32(hexadecimalnum, 16);
        BinaryTxt.Text = Convert.ToString(temp, 2);
    }
    // the condition is not true so print out a invalid number message
    else
    {
        MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
    }

CodePudding user response:

So, after some testing and googling, I think it's your regex pattern.

Another answer here worked: Validate hexadecimal string using regular expression

I tested the match and it worked fine. "^(0x|0X)?[a-fA-F0-9] $"

if you don't want the 0x, go with: "^[a-fA-F0-9] $"

I find that using an online tester like http://regexstorm.net/tester helps.

CodePudding user response:

try this solution:

if (Regex.IsMatch(s, @"\A\b[0-9a-fA-F] \b\Z"))
{
     int temp = int.Parse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber);
     DecimalTxt.Text= temp.ToString();
     BinaryTxt.Text = Convert.ToString(temp, 2); 
} 
else
{
     MessageBox.Show("Invalid - please enter a hexadecimal value in this box");
}

or you can use TryPrase() Int64_TryParse to check if string is valid

long temp ;
if(long.TryParse(hexadecimalnum, System.Globalization.NumberStyles.HexNumber, null, out  temp))
{
    DecimalTxt.Text= temp.ToString();
    BinaryTxt.Text = Convert.ToString(temp, 2); 
}
  • Related