Reputation: 3592
I am having a Dictionary<int,ulong>
, where I want to store StudentId
and his/her registered courses
(which is guaranteed to be 2).
Now, As you can see, instead of saving 2 courseids into a List
of Integers, i want to store them as ulong
as ulong
occupy 64 bits and int
occupy 32 bits.
So my question is, how can i combine these 2 integer ids and store them into a ulong
variable. I've tried with some Bitwise operation and shifting but unable to figure it out.
Upvotes: 2
Views: 1067
Reputation: 726629
"Packing" the data of two int
s into 64 bits can be accomplished without ulong
, for example like this:
Dictionary<int,ValueTuple<int,int>>
ValueTuple<int,int>
takes exactly as much space as ulong
, but it lets you access individual int
s through its properties.
If you must use ulong
, here is one approach that lets you pack and unpack int
s:
private static ulong Combine(int a, int b) {
uint ua = (uint)a;
ulong ub = (uint)b;
return ub <<32 | ua;
}
private static void Decombine(ulong c, out int a, out int b) {
a = (int)(c & 0xFFFFFFFFUL);
b = (int)(c >> 32);
}
Upvotes: 6