二进制存储数据

二进制存储数据

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

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;
    }
相关推荐
Dicky-_-zhang几秒前
服务网格实战:Istio与Linkerd对比选型与落地实践
java·jvm
云烟成雨TD2 分钟前
Spring AI Alibaba 1.x 系列【56】SAA Admin 平台功能介绍
java·人工智能·spring
Gauss松鼠会2 分钟前
GaussDB(DWS) 资源监控Topsql
java·网络·数据库·算法·oracle·性能优化·gaussdb
夏日听雨眠3 分钟前
数据结构(快速排序)
java·数据结构·算法
薇茗4 分钟前
【初阶数据结构】 升沉有序的平仄 排序 3
c语言·开发语言·数据结构·算法·排序算法·文件归并排序
字节高级特工6 分钟前
C++11(一) 革新:右值引用与移动语义
java·开发语言·c++·人工智能·后端
薇茗6 分钟前
【初阶数据结构】 升沉有序的平仄 排序 2
c语言·数据结构·算法·排序算法·快排精讲
郝学胜-神的一滴7 分钟前
系统设计 012:从用户系统出发,吃透缓存、数据库与高并发设计
java·数据库·python·缓存·php·软件构建
AI科技星11 分钟前
强哥德巴赫猜想(1+1)终极证明(2026 年5月 21 日)
开发语言·人工智能·算法·计算机视觉·量子计算
人道领域11 分钟前
【LeetCode刷题日记】654.最大二叉树:递归算法详解
java·算法·leetcode