2

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.

4

1 回答 1

6

可以不用将两个 s 的数据“打包”int成 64 位ulong,例如这样:

Dictionary<int,ValueTuple<int,int>>

ValueTuple<int,int>占用与 一样多的空间ulong,但它允许您int通过其属性访问单个 s。

如果您必须使用ulong,这里有一种方法可以让您打包和解包ints:

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

演示。

于 2018-04-27T13:46:36.627 回答