简体   繁体   中英

Combine 2 integers and store it in a ulong

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.

"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);
}

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM