二进制存储数据

二进制存储数据

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

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;
    }
相关推荐
Tony Bai5 分钟前
Go 语言的“魔法”时刻:如何用 -toolexec 实现零侵入式自动插桩?
开发语言·后端·golang
未若君雅裁7 分钟前
SpringAI基础入门
java·spring boot·ai
CC.GG14 分钟前
【C++】用哈希表封装myunordered_map和 myunordered_set
java·c++·散列表
Coding茶水间30 分钟前
基于深度学习的交通标志检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
a努力。40 分钟前
字节Java面试被问:TCP的BBR拥塞控制算法原理
java·开发语言·python·tcp/ip·elasticsearch·面试·职场和发展
jiaguangqingpanda1 小时前
Day24-20260120
java·开发语言·数据结构
m0_502724951 小时前
飞书真机调试
开发语言·前端·javascript
52Hz1181 小时前
力扣24.两两交换链表中的节点、25.K个一组反转链表
算法·leetcode·链表
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #160:相交链表(双指针法、长度差法等多种方法详细解析)
算法·leetcode·链表·双指针·相交链表·长度差法
一个龙的传说1 小时前
xshell下载
java