John Hang
John Hang

Reputation: 125

How do you convert a string to a long so it can be used to read binary bytes in C#?

So my project is to pull the offset from an ini file. The keyName is the offset. The keyValue contains the items to display. I'm getting an error when trying to convert the string to a long when reading the keyName from the ini.

Error: This exception was originally thrown at this call stack: System.Number.StringToNumber(string, System.Globalization.NumberStyles, ref System.Number.NumberBuffer, System.Globalization.NumberFormatInfo, bool) System.Number.ParseInt64(string, System.Globalization.NumberStyles, System.Globalization.NumberFormatInfo) long.Parse(string) CSOTN.CSOTN.BLoad_Click(object, System.EventArgs) in Form1.cs System.Windows.Forms.Control.OnClick(System.EventArgs) System.Windows.Forms.Button.OnClick(System.EventArgs) System.Windows.Forms.Button.OnMouseUp(System.Windows.Forms.MouseEventArgs) System.Windows.Forms.Control.WmMouseUp(ref System.Windows.Forms.Message, System.Windows.Forms.MouseButtons, int) System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message) System.Windows.Forms.ButtonBase.WndProc(ref System.Windows.Forms.Message) ... [Call Stack Truncated]

                        //Test String
                        string teststring = "0x2253";

                        long offset = long.Parse(teststring);


                        br.BaseStream.Position = offset;
                        itemvalues = br.ReadByte().ToString("X2");

                        //Test output
                        Messagebox.Show(itemvalues)

Upvotes: 0

Views: 243

Answers (1)

yaakov
yaakov

Reputation: 5850

Convert.ToInt64 has an overload that lets you convert text from different bases.

In this case, since your string starts with 0x, it's likely hexadecimal, or base-16.

You can therefore parse it simply like this:

Convert.ToInt64("0x2253", 16)

Upvotes: 1

Related Questions