0

I have a number of files that are named in TAI64N format here is a reference. When I try using this source it comes out negative with the assist of BitConverter.ToInt64

static void Main ( string[] args ) {
    string[] filenames = new string[4]{
        "4000000057b23bf30017a4bc",
        "4000000057b23ef61dedacac",
        "4000000057b24b1c2bab0614",
        "4000000057b24ca521a230fc"
    };
    foreach (string filename in filenames) {
        byte[] hexToBytes = StringToByteArray(filename);
        long bytesToLong = BitConverter.ToInt64(hexToBytes, 0);
        Console.WriteLine(bytesToLong); // Negative?
        DateTime longToDateTime = new DateTime(bytesToLong);
    }
}

public static byte[] StringToByteArray ( string hex ) {
    return Enumerable.Range(0, hex.Length)
        .Where(x => x % 2 == 0)
        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
        .ToArray();
}

What am I doing wrong?

Community
  • 1
  • 1
Vnsax
  • 67
  • 4

1 Answers1

0

Have you considered the difference between endiannes of your TAI64N value and your processor? I assume that you are using x86-64 processor, which is little endian, while the TAI64N value is big-endian. Methods of BitConverter class use processor endianness to convert values (see Remarks section).

I suggest you try reversing the order of bytes in array:

public static byte[] StringToByteArray ( string hex ) {
    byte[] arr = Enumerable.Range(0, hex.Length)
        .Where(x => x % 2 == 0)
        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
        .ToArray();
    Array.Reverse(arr);
    return arr;
}

And subsequently long bytesToLong = BitConverter.ToInt64(hexToBytes, 4);

By the way, I've noticed is that you use new DateTime(long ticks) constructor (reference), but you supply it with seconds (according to TAI64N specification) instead of ticks.

GKalnytskyi
  • 579
  • 7
  • 16