二进制存储数据

二进制存储数据

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

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;
    }
相关推荐
月落归舟8 小时前
带你了解Collections和Collection!!!
java·collections·collection
直奔標竿8 小时前
Java开发者AI转型第二十课!Spring AI MCP 双向实战:客户端与服务端手把手落地
java·开发语言·人工智能·spring boot·后端·spring
天码-行空8 小时前
深入拆解 Tomcat 架构:高层组件与启动流程设计
java·架构·tomcat
天码-行空8 小时前
深入拆解 Tomcat 架构:一键启停与生命周期设计
java·架构·tomcat
成都易yisdong8 小时前
高程异常计算器:一款集成Geoid、重力场与地磁场的专业工具
算法
weisian1518 小时前
进阶篇-LangChain篇-20--从零构建企业大脑:RAG系统全流程实战
开发语言·langchain·rag·实战编码
lly2024068 小时前
Kotlin 基础语法
开发语言
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【反悔贪心】:种树
c++·算法·贪心·反悔贪心·csp·信奥赛·种树
WHS-_-20228 小时前
Attention-Guided Low-Rank Tensor Completion
开发语言·php