0

In working with hexadecimal (strings stored in a database), integer and binary numeric representations, what is the difference between the folowwing 2 ways of converting from hexadecimal to integer:

List<string> hexadecimals = new List<string>
{
    "A1F9",
    "D",
    "BF17D0015",
    "972AB"
};

foreach(var hexadecimal in hexadecimals)
{
    var i1 = Convert.ToInt64(hexadecimal, 16);
    var i2 = Int64.Parse(hexadecimal, NumberStyles.HexNumber);

    Console.WriteLine($"hexa: {hexadecimal}, converted: {i1}, parsed: {i2}. Are equal: [{i1.Equals(i2)}]");
}
  1. Convert.ToInt64(hexadecimal, 16);
  2. Int64.Parse(hexadecimal, NumberStyles.HexNumber);

Should I prefer one to another ?

Output:

enter image description here

Veverke
  • 9,208
  • 4
  • 51
  • 95
  • Why would you store numbers as strings in database? – kiziu Sep 20 '16 at 08:16
  • agree with @kiziu. storing string in database will only waste space. use int instead. – active92 Sep 20 '16 at 08:29
  • I think [this answer](http://stackoverflow.com/a/199484/5246145) is also valid for Hex. – 3615 Sep 20 '16 at 09:55
  • Honestly, this is simply me getting familiar with my new workplace/system. And this question is an expression of me trying to analyse/understand things :) As far as I know, security permissions are stored in a database field as a hexadecimal string. How would you do that with an int or something else ? The point here, as it was handed over to me, was exactly trying to save space/minimize the data amounts to be transferred per client request. – Veverke Sep 20 '16 at 09:58
  • @Veverke you may check the difference at [referencesource](http://referencesource.microsoft.com/). – Sergey.quixoticaxis.Ivanov Sep 20 '16 at 10:04
  • @3615: Could be, but here there is a peculiarity with the Convert approach, in which you can get the representation for bases 2, 8, 16. With Parse you can only to hexa (the NumberStyles enumeration does not have an Octet/Binary). – Veverke Sep 20 '16 at 10:13
  • 1
    @Sergey.quixoticaxis.Ivanov: turns out it is not that simple to drill down to the implementation of the underlying method call `public unsafe extern static long StringToLong(System.String s, int radix, int flags, int* currPos);` – Veverke Sep 20 '16 at 11:54
  • @Veverke ah, no luck then. Most of Convert methods (at least the ones I inspected) were implemented in C# =( – Sergey.quixoticaxis.Ivanov Sep 20 '16 at 11:58

0 Answers0