1

i have a string variable that contains a hex value. What i want is to convert this string to an integer so i can subtract this value with another hex value. Code below:

string im_cmd = new string(ch3) //ch3 is char array type (ch3[])
im_cmd = myArray[position, 0]; // get the hex value from myArray
int vh = Convert.ToInt32(im_cmd);
int diff = vh - pc;
im_cmd = Convert.ToString(Convert.ToInt32(diff.ToString(), 16), 2);

for instance, if im_cmd = 00400004, then the variable vh = 0x00061a84 what i want is vh = 0x00400004 so i can subtract vh with the pc value that contains only hex values. any ideas?

1 Answer 1

3

The Convert.ToInt32 method has an overload where you can supply the base:

int vh = Convert.ToInt32(im_cmd, 16);

UPDATE:
Hint: Instead of

im_cmd = Convert.ToString(Convert.ToInt32(diff.ToString(), 16), 2);

you can use

im_cmd = String.Format("{0:x}", diff);

to output the integer as a HEX-string.

1
  • it works! i also tried int vh = int.Parse(im_cmd,System.Globalization.NumberStyles.HexNumber); and is the same result as your answer! thanks again! Commented Oct 16, 2014 at 12:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.