none
Converting a char into a hexadecimal number RRS feed

  • Question

  • so I have this : 

            int ConvertIntoNumber(char c)
            {
                int tempNumber = 0;
                char[] tempC = new char[1];
                tempC[0] = c; 
                string temp = new string(tempC);
                switch(c)
                {
                    case 'A':
                        tempNumber = 10;
                    break;
                    case 'B':
                        tempNumber = 11;
                        break;
                    case 'C':
                        tempNumber = 12;
                        break;
                    case 'D':
                        tempNumber = 13;
                        break;
                    case 'E':
                        tempNumber = 14;
                        break;
                    case 'F':
                        tempNumber = 15;
                        break;
    
                    default:
                        {
                            tempNumber = int.Parse(temp);
                            break;
                        }
    
    
                }
    
                return tempNumber;
            } 


    and that works, just wanted to know if there is a cleaner way of doing this? just seems weird that I have to convert it in to a string 1st. 

    Wednesday, June 17, 2020 10:31 PM

All replies

  • Hi btb900,

    Thank you for posting here.

    Try this:

            int ConvertIntoNumber(char c)
            {
                string str = c.ToString();
                int int_value = Convert.ToInt32(str, 16);
                return int_value;
            }

    Or

     int re = int.Parse(str, NumberStyles.HexNumber);

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 18, 2020 1:35 AM
  • Hi,

    Has your issue been resolved?

    If so, please click on the "Mark as answer" option of the reply that solved your question, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, July 10, 2020 9:50 AM