Reputation: 185
I am trying to take a user defined decimal value from a textBox, convert to a hex (with the 0x) prefix then store that value to an integer. I'm currently stuck at getting the 0x prefix, but maybe there is a more appropriate way to accomplish this.
string decimalString = textBox1.Text;
//Convert decimalString string into an int
int decimalNumber = int.Parse(decimalString);
//Convert decimalNumber to a hex string
string hexString = decimalNumber.ToString("X");
Console.Write(decimalNumber);
//TextBox Input: 151
//Console Output: 97
//Desired Output: 0x97 (as a string, but would like to assign to int if possible).
int finalDesiredOutput = 0x97;
Hope I am explaining this well.
In this project I'm trying to replace the 13th byte in a header with a decimal value between 0-2600 (user entered value). It's easier for a user to enter a decimal as opposed to a hex value (i.e. 2600, rather than A28).
Upvotes: 2
Views: 6703
Reputation: 11
StringBuilder sb = new StringBuilder();
string hex = "C26B3CB3833E42D8270DC10C";
for (int i = 0; i < hex.Length; i++)
{
if(i%2==0)
{
sb.Append(",0x").Append(hex.Substring(i, 2));
}
}
Console.WriteLine(sb.ToString());
Upvotes: 0
Reputation: 29026
What about String.Format()
string hexString =String.Format("0X{0:X}", decimalNumber);
Upvotes: 6