-2

I have this code:

string IDNumber = "0x0037D70D";

long x = 0x0037D70D; //Working

long x = long.Parse(IDNumber); //Error Input string was not in a correct format.

Required to send the string above (IDNumber) to long y and should maintain the variable format and value typical as its start with 0x.... same as in the IDNumber string

Kindly help me.

Edit:

I have function in DLL file, this function accept one parameter with data type long

If I give this long parameter the value like 0x0037D70D then the function is working correctly and do the required job but if I give the long parameter the value in any other format like 3659533 function is not working

string example1 = "0x0037D70D";
long example2 = 0x0037D70D;

At the end I have the value coming in string format like example1 which I want to convert to be like example2 because if I have the value written like example2 format and saved in long variable then is working

Update: The problem solved, I use this function to communicate with external hardware device and after many times trying the device hangs, I rest the device and the solution advised by @Kirill Polishchuk working for me.

long l = Convert.ToInt64(IDNumber, 16);

2 Answers2

1

You should remove 0x prefix:

long y = long.Parse(IDNumber.Replace("0x", ""), System.Globalization.NumberStyles.HexNumber);
long x = 0x0037D70D; //Working
Console.WriteLine(x.ToString("X")); //prints "37D70D", no prefix
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

I would suggest using Convert class:

long l = Convert.ToInt64(IDNumber, 16);
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • This will convert the hexadecimal to integer and the result will be 3659533 and not 0x0037D70D – Waleed ELerksosy Jun 25 '20 at 07:20
  • @WaleedELerksosy ...and what exactly is wrong with that? [`0x0037D70D` is a hexadecimal representation of `3659533`](https://i.stack.imgur.com/xU9hv.png). What else could you possibly be trying to do? If you want it in a hexadecimal (string) format, why are you converting it to a long? – ProgrammingLlama Jun 25 '20 at 07:50
  • I have function in DLL file, this function accept one parameter with data type long If I give this parameter the value like 0x0037D70D then the funcation is working correctly and do the required job but if I do it in any other format like 3659533 function is not working string example1 = "0x0037D70D"; long example2 = 0x0037D70D; At the end I have the value coming in string format like example1 which I want to convert to be like example2 because if I have the value written like example2 then is working – Waleed ELerksosy Jun 25 '20 at 08:21
  • 1
    Thank you, problem solved :) – Waleed ELerksosy Jun 25 '20 at 09:15
  • @WaleedELerksosy, cool – Kirill Polishchuk Jun 28 '20 at 22:03