A GUID can never be long, because, as I said, the GUID is 16 bytes and the long is 8 bytes. You cannoy will gladly drop 8 bytes from the GUID, even if they are zeros! :-)
A Guid is just a 128-bit data structure, and a long one is a 64-bit data structure ...
This means that as long as the top 64 bits are Zeroes, we can safely discard them later to restore them, since Zeroes do not mean complete data in this case. So yes, this is data loss, but in circumstances it is data loss that can be recovered. (Think in terms of compression)
This is no different from what you say:
long x = 5000;
These explicit conversions are not built into the system, since this does not mean that you need to do this differently.
public static Guid ToGuid(long value) { byte[] guidData = new byte[16]; Array.Copy(BitConverter.GetBytes(value), guidData, 8); return new Guid(guidData); } public static long ToLong(Guid guid) { if (BitConverter.ToInt64(guid.ToByteArray(), 8) != 0) throw new OverflowException("Value was either too large or too small for an Int64."); return BitConverter.ToInt64(guid.ToByteArray(), 0); }
Obviously, this should never be used with a genneral GUID, but it is safe to use as long as the GUID has only 64 bits of "actual data", the best way to ensure that it will never use it on pins unless they are created using long.
As a precaution, I added throwing an OverflowException in cases when the Guid actually stores anything other than 0 in the last 64 bits, since the resulting one cannot be converted back to the same Guid for a long time.
So, as such ...
As long as the created guid fits in long, is that possible? It is simple when it passes a long specified size. Right?
Is true ... Obviously the corresponding long GUID value is not easy to read, here are a few examples (long = guid):
1.340 = 0000053c-0000-0000-0000-000000000000 98.605 = 0001812d-0000-0000-0000-000000000000 149.957 = 000249c5-0000-0000-0000-000000000000 218.125.225 = 0d0053a9-0000-0000-0000-000000000000 4.249.596.910 = fd4bb3ee-0000-0000-0000-000000000000 23.139.913.545 = 633f0f49-0005-0000-0000-000000000000 9.223.372.036.854.775.807 = ffffffff-ffff-7fff-0000-000000000000 -9.223.372.036.854.775.808 = 00000000-0000-8000-0000-000000000000 -1 = ffffffff-ffff-ffff-0000-000000000000
And yes, the conversion of these works in both directions and for any long value you can come up with ...
But since you declare that:
Guid creation is out of my control.
It is extremely unlikely that you really can do this, but most likely that you have a Guid generated using any of the common algorithms, and this will make Guid unusable in this scenario.
Now it makes sense to do? ... It requires an understanding of the specific situation and is another discussion ...