-1

This is a small snippet of the code I have written in Visual Studio. I need to convert the int add into an hex value (later into a string) as I am accessing the memory of a uC. But when I view the variable during debugging it displays it as a string "add16". What could I be doing wrong?

for (int add = 0; add <= 0xfffff; )
{
    for (int X = 0; X <= 15; X++)
    {
        string address = add.ToString("add16");
        addr = Convert.ToString(address);
        port.WriteLine(String.Format("WRBK:{0}:{1}", addr, parts[X]));
        add++;
    } 
}
game_the
  • 11
  • 3
  • The other answers here will all work, but I would suggest looking through the [numeric format strings](https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx#XFormatString) to understand why your way doesn't work. You can use `ToString()` to get a hexadecimal string from an int, but you have to pass in the right format string, e.g. `add.ToString("X")`. – Matthew Jaspers Feb 13 '15 at 22:01
  • I would point out that you cannot "convert an int to hex", you can only convert it to a hex string. – Dave Cousineau Feb 13 '15 at 22:05

2 Answers2

2

There is a simple and very convenient method that takes an integer and returns a representation of it as a string in hexadecimal notation

string address = Convert.ToString(add, 16);

So, perhaps, your internal loop could be rewritten as

port.WriteLine(String.Format("WRBK:{0}:{1}", Convert.ToString(add++, 16), parts[X]));

and using the standard numeric format strings specifiers reduced to

port.WriteLine(String.Format("WRBK:{0:X}:{1}", add++, parts[X]));
Steve
  • 213,761
  • 22
  • 232
  • 286
2

You can tell .NET's String.Format to use hex output for the integer, eliminating any code to hex conversion, use:

port.WriteLine(String.Format("WRBK:{0:X}:{1}", add, parts[X]));
Bas
  • 26,772
  • 8
  • 53
  • 86