I need to develop an ever increSing counter in C#. I am thinking about converting GUID to long. Is that possible in c#? Is there any other way to develop an ever increasing counter?
-
why you want convert GUID to long, if you need a counter? – Tigran Jul 12 '11 at 19:51
-
9i don't think i understand the question because you don't need a GUID for this. if you just need a counter, you would just use `long Counter=0;` and then could call `long x = Counter;` when you needed to use it and `++Counter` to increment it. can you clarify why you need it as a GUID? – shelleybutterfly Jul 12 '11 at 19:51
-
1possible duplicate of [How to Convert Long to Guid and Vice Versa?](http://stackoverflow.com/questions/3900703/how-to-convert-long-to-guid-and-vice-versa) – Jul 12 '11 at 19:55
-
We are also looking to get a unique uInt64 with out explicitly persisting it. – Zapnologica Apr 13 '15 at 09:24
4 Answers
No, a GUID is 128 bit so won't fit in your long since that is 64 bit. A System.Decimal is 128 bit so will get you a long way, but of course that also has it's limits. Even if you save your counter in a string it has its limits. Computers alsways have limits, you will have to find one which is big enough so you can continue for a while.
edit:
In .Net 4.0 there is a BigInteger which can be pretty big, but remember, even that has its limits since it has to fit in memory.

- 42,837
- 6
- 126
- 143
you could try something like this.
byte[] gb = Guid.NewGuid().ToByteArray();
int i = BitConverter.ToInt32(gb,0);
long l = BitConverter.ToInt64(gb,0);
I am not sure If it is very secure. :p

- 5,914
- 2
- 22
- 21
-
I'm sure it is not. But it doesn't matter because security wasn't mentioned as requirement – sehe Jul 12 '11 at 20:07
-
8That just takes the beginning bytes of the array, thus making the result *by far not as unique as the GUID with which it was fed*!!!!!!!! (this needs more exclamation marks!) – Ray Mar 21 '16 at 19:43
-
2
A GUID is a 128-bit integer. A long is a Signed 64-bit integer. While a ulong can have values from 0 to 18,446,744,073,709,551,615. Is that enough? Or do you wish to use decimal?

- 2,515
- 2
- 22
- 26
The problem is that the set of GUID far outnumbers the set of all integers long precision. So really you are shrinking the cardinality of choices significantly. There is no good reason to do this.
If you want to keep increasing a number and not worry about it, there's a library IntX that handles big numbers. You could store the local state of your number generator in a file or in memory and you'll have an ever increasing number. (well sort of)

- 30,469
- 8
- 53
- 60