gpt4 book ai didi

java - 如何从数字中检索位

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:07 25 4
gpt4 key购买 nike

有时我会遇到下面的代码。我相信它用于将值表示为位,它们可以组合成一个数字并在以后检索。

数字 34 由 0100000000000100232 组成。我如何在 Java 中解决这个问题?不知何故,我必须将 2 与某个变量进行比较以执行 X,将 32 与另一个变量进行比较以执行 Y

以下是我的一些想法的例子。

来自 DotA modding wiki。

DOTA_ABILITY_BEHAVIOR_HIDDEN               = 1 << 0, //Can be owned by a unit but can't be cast and won't show up on the HUD.
DOTA_ABILITY_BEHAVIOR_PASSIVE = 1 << 1, //Cannot be cast like above but this one shows up on the ability HUD.
DOTA_ABILITY_BEHAVIOR_NO_TARGET = 1 << 2, //Doesn't need a target to be cast, ability fires off as soon as the button is pressed.
DOTA_ABILITY_BEHAVIOR_UNIT_TARGET = 1 << 3, //Needs a target to be cast on.
DOTA_ABILITY_BEHAVIOR_POINT = 1 << 4, //Can be cast anywhere the mouse cursor is (if a unit is clicked it will just be cast where the unit was standing).
DOTA_ABILITY_BEHAVIOR_AOE = 1 << 5, //Draws a radius where the ability will have effect. Kinda like POINT but with a an area of effect display.
//...

所以这些“行为”被存储为 1、2、4、8、16、32 等。但是整个想法似乎能够将多种类型存储到一个数字/字节中并在以后检索它们。我看到这样的用法:

DOTA_ABILITY_BEHAVIOR_AOE | DOTA_ABILITY_BEHAVIOR_PASSIVE

这似乎是 34。唯一会产生 34 的组合是这个 DOTA_ABILITY_BEHAVIOR_AOE | DOTA_ABILITY_BEHAVIOR_PASSIVE 并且我相信,只要您不两次使用相同的值,以这种方式进行的每个组合都是独一无二的。

那么如何从数字34 中检索这两个数字呢?这样使用有什么限制吗?

最佳答案

那些特殊的数字被称为位掩码,用于设置和读取二进制标志
一个字节shortintlong 值因此可以包含多个这些标志。

例子:

int flag1 = 0b0000001; // 1<<0, or 1
int flag2 = 0b0000010; // 1<<1, or 2
int flag3 = 0b0000100; // 1<<2, or 4

组合标志:

int combined= flag1 | flag2;

设置标志:

combined = combined | flag3;

取消标记:

combined = combined & ~flag;

检查是否设置了标志:

boolean set3 = (combined & flag3) !=0;

关于java - 如何从数字中检索位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36125237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com