• Bitmap 位操作相关


    见: https://www.jianshu.com/p/6082a2f7df8e

    了解一个结构,起码得知道怎么增,删,改,查吧。

    BitMap就像是一个二维矩阵一样,m*n,其中n固定为8(1byte = 8 bit),则

      index = value / 8 = value >> 3; 

      position = value % 8 ,模八,也即看最低三位是什么,因为最低三位肯定除不尽8,就是最终的余数。  所以即 value & 0111 即可,即0x07 

           

     1 public class BitMap {
     2     //保存数据的
     3     private byte[] bits;
     4     
     5     //能够存储多少数据
     6     private int capacity;
     7     
     8     
     9     public BitMap(int capacity){
    10         this.capacity = capacity;
    11         
    12         //1bit能存储8个数据,那么capacity数据需要多少个bit呢,capacity/8+1,右移3位相当于除以8
    13         bits = new byte[(capacity >>3 )+1];
    14     }
    15     
    16     public void add(int num){
    17         // num/8得到byte[]的index
    18         int arrayIndex = num >> 3; 
    19         
    20         // num%8得到在byte[index]的位置
    21         int position = num & 0x07; 
    22         
    23         //将1左移position后,那个位置自然就是1,然后和以前的数据做|,这样,那个位置就替换成1了。
    24         bits[arrayIndex] |= 1 << position; 
    25     }
    26     
    27     public boolean contain(int num){
    28         // num/8得到byte[]的index
    29         int arrayIndex = num >> 3; 
    30         
    31         // num%8得到在byte[index]的位置
    32         int position = num & 0x07; 
    33         
    34         //将1左移position后,那个位置自然就是1,然后和以前的数据做&,判断是否为0即可
    35         return (bits[arrayIndex] & (1 << position)) !=0; 
    36     }
    37     
    38     public void clear(int num){
    39         // num/8得到byte[]的index
    40         int arrayIndex = num >> 3; 
    41         
    42         // num%8得到在byte[index]的位置
    43         int position = num & 0x07; 
    44         
    45         //将1左移position后,那个位置自然就是1,然后对取反,再与当前值做&,即可清除当前的位置了.
    46         bits[arrayIndex] &= ~(1 << position); 
    47 
    48     }
    49     
    50     public static void main(String[] args) {
    51         BitMap bitmap = new BitMap(100);
    52         bitmap.add(7);
    53         System.out.println("插入7成功");
    54         
    55         boolean isexsit = bitmap.contain(7);
    56         System.out.println("7是否存在:"+isexsit);
    57         
    58         bitmap.clear(7);
    59         isexsit = bitmap.contain(7);
    60         System.out.println("7是否存在:"+isexsit);
    61     }
    62 }
    View Code

     统计一个int对应二进制的1的个数:

     1 int countOne(int num)  
     2 {  
     3     int count = 0;  
     4     if(num < 0) {
     5         num = - num;
     6         count++;
     7     }
     8     while ( num != 0 )  
     9     {  
    10         count += value & 1;
    11         num >>= 1;  
    12     }  
    13         return count;  
    14 }  
    View Code

  • 相关阅读:
    2021 Duilib最新入门教程(二)Duilib编译动态库
    2021 Duilib最新入门教程(一)Duilib简介
    webgl图库选型
    CUDA编程学习记录
    C++时间戳获取
    FFMPEG编译问题记录
    程序员的35岁
    Linux发行版及其目标用户
    服务器关机或重启
    Linux下找出吃内存的方法总结
  • 原文地址:https://www.cnblogs.com/ddcckkk/p/8621659.html
Copyright © 2020-2023  润新知