0

So my class assignment is to make our own algorithm not using the built in functions that converts an int to hexidecimal and for the life of me it will not comply.

The example in our text converts 24032 to 0x5DE0 but what I am getting as output is 3210.

This is my code

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    List<string> errorList = new List<string>();
    List<int> hexList = new List<int>();
    string intInput = "";
    string msgOutput = "";

    private void btn_Hex_Click(object sender, EventArgs e)
    {
        intInput = box_Int.Text;
        int toHexFunc = Validator(intInput);
        ToHex(toHexFunc);
    }

    public void ToHex(int fromHexBtn)
    {
        int n = fromHexBtn;
        char[] hexNum = new char[100];
        int i = 0;
        while (n != 0)
        {
            int iterTemp = n % 16;

            // using ASCII table from https://www.dotnetperls.com/ascii-table
            if (iterTemp < 10)
            {
                hexNum[i] = (char)(iterTemp + 48);
                i++;
            }
            else
            {
                hexNum[i] = (char)(iterTemp + 55);
                i++;
            }

            n = n / 16;
        }

        for (int j = i - 1; j >= 0; j--)
        {
            hexList.Add(j);
        }

        msgOutput = String.Join("", hexList);
        lbl_Message.Text = msgOutput;

        
    }
}

    
KyleC
  • 29
  • 7
  • 3
    Does this answer your question? [Convert integer to hexadecimal and back again](https://stackoverflow.com/questions/1139957/convert-integer-to-hexadecimal-and-back-again) – eglease Nov 15 '21 at 15:07
  • Unfortunately no, those solutions use the built in converters, and the longer code at the bottom converts byte to hex which is obviously not useful in this case either. Mine has to be a new algorithm from scratch. – KyleC Nov 15 '21 at 15:15
  • 1
    you can see here https://stackoverflow.com/questions/40322745/convert-int-to-hex-string-without-using-integer-tohexstring to understand the algorithm – Majid Ramezankhani Nov 15 '21 at 15:21
  • why do you need a new one? – Leandro Bardelli Nov 15 '21 at 15:26
  • That's the assignment. The class wants us to focus on using loops and arrays/lists, the datatype conversion is just what they decided to have us do. – KyleC Nov 15 '21 at 16:03

1 Answers1

0

base on this https://www.permadi.com/tutorial/numDecToHex/

class Program
{
    static void Main(string[] args)
    {
       var characters = "0123456789ABCDEF";

       int number = 24032;

       var hexidecimal = "";

       while (number > 0)
       {
          var remainder = number % 16;
          var res = Math.Abs(number / 16);

          hexidecimal = characters[remainder] + hexidecimal;

          number = res;
        }

        hexidecimal = "0x" + hexidecimal;

        WriteLine(hexadecimal);
   }
}