二进制存储数据

二进制存储数据

案例是一个图鉴是否解锁的二进制转换代码

java 复制代码
public class MonsterBook {

    public static void main(String[] args) {
        List<Long> monsterList = init(32);
        for (int i = 1; i <= 30; i++) {
            addMonster(i, monsterList);
        }

        for (Long l : monsterList) {
            System.out.println(l);
        }

        System.out.println("\n==================\n");

        List<Integer> allSeenMonster = getAllSeenMonster(monsterList);
        for (Integer i : allSeenMonster) {
            System.out.println(i);
        }

    }

    private static List<Long> init(int size) {
        int amount = (size / 64) + 1;
        List<Long> monsterBookList = new ArrayList<>();
        for (int i = 0; i < amount; i++) {
            monsterBookList.add(0L);
        }
        return monsterBookList;
    }

    private static boolean addMonster(int monsterSortId, List<Long> monsterBookList) {
        monsterSortId = monsterSortId - 1;
        int indexOfList = monsterSortId / 64;
        int indexOfLong = monsterSortId % 64;
        long oldLongValue = monsterBookList.get(indexOfList);
        long newLongValue = oldLongValue | (1L << indexOfLong);
        if (oldLongValue != newLongValue) {
            monsterBookList.set(indexOfList, newLongValue);
            return true;
        }
        return false;
    }

    private static int getBit(long longValue, int index) {
        return (int) ((longValue >> index) & 1L);
    }

    private static List<Integer> getAllSeenMonster(List<Long> monsterBookList) {
        ArrayList<Integer> result = new ArrayList<>();
        for (int indexOfList = 0; indexOfList < monsterBookList.size(); indexOfList++) {
            long longValue = monsterBookList.get(indexOfList); // 不转换为int
            for (int indexOfPos = 0; indexOfPos < 64; indexOfPos++) {
                int bit = getBit(longValue, indexOfPos);
                if (bit == 1) {
                    int sortId = indexOfList * 64 + indexOfPos + 1;
                    result.add(sortId);
                }
            }
        }
        return result;
    }
相关推荐
两个蝴蝶飞1 小时前
Java量化系列(四):实现自选股票维护功能
java·经验分享
半桶水专家3 小时前
go语言中的结构体嵌入详解
开发语言·后端·golang
短剑重铸之日3 小时前
7天读懂MySQL|Day 5:执行引擎与SQL优化
java·数据库·sql·mysql·架构
酒九鸠玖3 小时前
Java--多线程
java
Dreamboat-L3 小时前
云服务器上部署nginx
java·服务器·nginx
长安er4 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓4 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
在屏幕前出油4 小时前
二、Python面向对象编程基础——理解self
开发语言·python
小白菜又菜4 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
阿方索4 小时前
python文件与数据格式化
开发语言·python