redis中bitmaps二进制转成BitSet

 上一篇讲 redis中bitmaps进行状态统计

  本篇讲redis中bitmaps二进制数据转换成JDK中BitSet数据

/**
* @Title: RedisServiceExtend
* @Description: redis 扩展
* @author chy
* @date 2018/5/8 8:27
*/
@Repository
public class RedisServiceExtend  {

    private static String redisCode = "utf-8";

    @Autowired
    RedisTemplate redisTemplate;

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    

    /**
     * 获取value
     * @param key
     * @return
     */
    public byte[] get(final String key){
        return redisTemplate.execute(new RedisCallback() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] result;
                result = connection.get(key.getBytes());
                return result;
            }
        });
    }
}
 @Test
    public void javaBitSet() {
        BitSet bitSet = new BitSet();

        bitSet.set(1, true);
        bitSet.set(2, true);
        bitSet.set(8, true);

        int count = bitSet.cardinality();

        // 从右往左

        // 2进制 0000 0001 0000 0110

        // 16进制   0    1    0    6

        // byte[0]=6   byte[1]=1
        byte[] bytes= bitSet.toByteArray();

        System.out.println("bytes: " + bytes.length);

        System.out.println("bit 为 1的位置: " + count);


        //redis 二进制数据转换
        String key2 = "20180503";
        redisDao.setBit(key2, 1, true);
        redisDao.setBit(key2, 2, true);
        redisDao.setBit(key2, 8, true);       

        //获取二进制数据
        byte[] vBytes =redisServiceExtend.get(key2);

        //转换
        BitSet rBitSet=fromByteArrayReverse(vBytes);

        byte[] rBytes= rBitSet.toByteArray();

        System.out.println("bytes: " + rBytes.length);

        System.out.println("bit 为 1的位置: " + rBitSet.cardinality());
    }
/**
     * redis中bitmaps二进制存储的结构是从左到右 
     * BitSets二进制存储的结构从右到左
     * @param bytes
     * @return
     */
    public static BitSet fromByteArrayReverse(final byte[] bytes) {
        final BitSet bits = new BitSet();
        for (int i = 0; i < bytes.length * 8; i++) {
            if ((bytes[i / 8] & (1 << (7 - (i % 8)))) != 0) {
                bits.set(i);
            }
        }
        return bits;
    }

 

你可能感兴趣的:(缓存)