二进制存储数据

二进制存储数据

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

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;
    }
相关推荐
Jerry952706282 小时前
1.什么式可用性
java·分布式·后端·架构·高可用·秒杀
laocooon5238578862 小时前
C++ 设计模式概述及常用模式
开发语言·c++·设计模式
爱潜水的小L2 小时前
自学嵌入式day28,文件操作
linux·数据结构·算法
2301_800399722 小时前
误用sizeof()计算指针
算法
黑客思维者2 小时前
Python自动化测试Pytest/Unittest深度解析与接口测试落地实践
开发语言·python·pytest·unittest
muyouking112 小时前
Zig 模块系统详解:从文件到命名空间,与 Rust 的模块哲学对比
开发语言·后端·rust
wbs_scy2 小时前
C++ :Stack 与 Queue 完全使用指南(基础操作 + 经典场景 + 实战习题)
开发语言·c++
君爱学习2 小时前
JVM对象分配内存如何保证线程安全?
java
ULTRA??2 小时前
QT向量实现GJK碰撞检测算法几何图形二维版本
c++·qt·算法