二进制存储数据
案例是一个图鉴是否解锁的二进制转换代码
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;
}