This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我正在阅读应使用byte数组实现位向量的代码。
这个想法是,如果在相应的位置出现数字,则位向量将设置位。
例如。如果存在数字10,则必须设置位10,依此类推。这是一个经典的概念,我明白了,但是我不确定实际的实现方式。

我没有得到的部分是:
bitvector [num / 8] |= 1 << (num % 8);

其中num是要设置的数字。
如果num为10,则必须使用第二个字节(到目前为止,num/8还可以),但是1 << (num % 8)不会像应有的那样设置第二个字节的第二个位。可以?

最佳答案

10 % 8 = 2,因此是1 << (10 % 8) = bit 2或值4(二进制为100)

(从字节的右边开始计数,从零开始)。验证非常简单:

7 -> 7 % 8 = 7, byte[0], Bit 7 (1 << 7).
8 -> 8 % 8 = 0, byte[1], Bit 0 (1 << 0).
9 -> 9 % 8 = 1, byte[1], Bit 1 (1 << 1).
10 -> 10 % 8 = 2, byte[1], Bit 2 (1 << 2).

09-10 07:15
查看更多