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

前端 未结 19 2434
不知归路
不知归路 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:20

    If you want more control such as allocate X bits for the first number and Y bits for the second number, you can use this code:

    class NumsCombiner
    {
    
        int num_a_bits_size;
        int num_b_bits_size;
    
        int BitsExtract(int number, int k, int p)
        {
            return (((1 << k) - 1) & (number >> (p - 1)));
        }
    
    public:
        NumsCombiner(int num_a_bits_size, int num_b_bits_size)
        {
            this->num_a_bits_size = num_a_bits_size;
            this->num_b_bits_size = num_b_bits_size;
        }
    
        int StoreAB(int num_a, int num_b)
        {
            return (num_b << num_a_bits_size) | num_a;
        }
    
        int GetNumA(int bnum)
        {
            return BitsExtract(bnum, num_a_bits_size, 1);
        }
    
        int GetNumB(int bnum)
        {
            return BitsExtract(bnum, num_b_bits_size, num_a_bits_size + 1);
        }
    };
    
    

    I use 32 bits in total. The idea here is that if you want for example that first number will be up to 10 bits and second number will be up to 12 bits, you can do this:

    NumsCombiner nums_mapper(10/*bits for first number*/, 12/*bits for second number*/);
    

    Now you can store in num_a the maximum number that is 2^10 - 1 = 1023 and in num_b naximum value of 2^12 - 1 = 4095.

    To set value for num A and num B:

    int bnum = nums_mapper.StoreAB(10/*value for a*/, 12 /*value from b*/);
    

    Now bnum is all of the bits (32 bits in total. You can modify the code to use 64 bits) To get num a:

    int a = nums_mapper.GetNumA(bnum);
    

    To get num b:

    int b = nums_mapper.GetNumB(bnum);
    

    EDIT: bnum can be stored inside the class. I did not did it because my own needs I shared the code and hope that it will be helpful.

    Thanks for source: https://www.geeksforgeeks.org/extract-k-bits-given-position-number/ for function to extract bits and thanks also to mouviciel answer in this post. Using these to sources I could figure out more advanced solution

提交回复
热议问题