Mapping two integers to one, in a unique and deterministic way

前端 未结 19 2115
不知归路
不知归路 2020-11-22 09:35

Imagine two positive integers A and B. I want to combine these two into a single integer C.

There can be no other integers D and E which combine to C. So combining

19条回答
  •  孤街浪徒
    2020-11-22 10:11

    If A and B can be expressed with 2 bytes, you can combine them on 4 bytes. Put A on the most significant half and B on the least significant half.

    In C language this gives (assuming sizeof(short)=2 and sizeof(int)=4):

    int combine(short A, short B)
    {
        return A<<16 | B;
    }
    
    short getA(int C)
    {
        return C>>16;
    }
    
    short getB(int C)
    {
        return C & 0xFFFF;
    }
    

提交回复
热议问题