Algorithm for copying N bits at arbitrary position from one int to another

前端 未结 7 1838
别那么骄傲
别那么骄傲 2021-01-31 21:36

An interesting problem I\'ve been pondering the past few days is how to copy one integer\'s bits into another integer at a given position in the destination integer. So, for exa

7条回答
  •  耶瑟儿~
    2021-01-31 22:20

    It pretty good: I tried this alternate version, but yours was about 30% faster in testing:

        int[] bits = new int[] {0,1,3,7,15,31,63,127,255,511,1023
            ,2047,4095,8192,16383,32767,65535,131071,262143,524287
            ,1048575,2097151,4194303,8388607,16777215,33554431,67108863
            ,134217727,268435455,536870911,1073741823,2147483647,-1};
    
        public int setbits2(int destination, int source, int at, int numbits)
        {
            int ones = bits[numbits + at] & ~bits[at];
            return (destination & ~ones) | ((source << at) & ones);
        }
    

提交回复
热议问题