niao
niao

Reputation: 5070

Convert decimal

I have for instance the following string: "0x780000105d0e0030" If this is not the string, I can easily get the value as follows:

ulong myValue = 0x780000105d0e0030;

which give me the value of: 8646911354832027696 However, when I want to parse it as follows:

var myValue2= Convert.ToInt64("0x780000105d0e0030",16)

which give me the value of: 8070450566607667200

Then, then myValue is different than myValue2. myValue is correct however and this is how it should work. What am I doing wrong?

Upvotes: 2

Views: 127

Answers (3)

Pete Kirkham
Pete Kirkham

Reputation: 49311

The value you are converting is within the range of Int64, and is converted to the equivalent Int64 value, as can be demonstrated by the following code:

ulong u = 0x780000105d0e0030;

Console.WriteLine("Convert.ToInt64(\"0x780000105d0e0030\", 16) => {0}", Convert.ToInt64("0x780000105d0e0030", 16));
Console.WriteLine("u                                         => {0}", u);
Console.WriteLine("u.ToString(\"x\")                           => {0}", u.ToString("x"));
Console.WriteLine("Convert.ToInt64(u.ToString(\"x\"), 16)      => {0}", Convert.ToInt64(u.ToString("x"), 16));
Console.WriteLine("u = (ulong)Convert.ToInt64(\"0x780000105d0e0030\", 16)");
u = (ulong)Convert.ToInt64("0x780000105d0e0030", 16);
Console.WriteLine("u                                         => {0}", u);

which results in the following output:

Convert.ToInt64("0x780000105d0e0030", 16) => 8646911354832027696
u                                         => 8646911354832027696
u.ToString("x")                           => 780000105d0e0030
Convert.ToInt64(u.ToString("x"), 16)      => 8646911354832027696
u = (ulong)Convert.ToInt64("0x780000105d0e0030", 16)
u                                         => 8646911354832027696

Which leaves two possibilities:

  1. The version of .net you are using (I have 4.0.30319 RTMRel) has a major flaw in the implementation of Convert.ToInt64
  2. You're passing in the string "0x7000000000000000" to the function instead.

My money would be on the latter explanation.

Upvotes: 2

pad
pad

Reputation: 41290

When myValue is unsigned Int64, myValue2 is signed Int64.

What you actually need is Convert.ToUInt64 function.

Upvotes: 3

Oded
Oded

Reputation: 498904

Int64 is a signed long.

Use Convert.ToUInt64 instead:

var myValue2= Convert.ToUInt64("0x780000105d0e0030",16);

Upvotes: 3

Related Questions