gpt4 book ai didi

java - 添加到数组的最小可能值?

转载 作者:行者123 更新时间:2023-11-30 03:03:29 25 4
gpt4 key购买 nike

根据我的阅读,您可以使用以下命令将字节存储在 PHP 的数组中:

 $array = [1,2,14,10];

我想添加到每个数组值的四个基本标志,例如 0000。如果用户执行了解锁第三个标志的操作,则该值应类似于 0010。如果设置了所有标志,则该值将类似于 1111

我计划拥有很多这些类型的数组值,所以我想知道我可以放入一个对 Java 友好的数组中的最小可能值是多少?将数据存储在 PHP 中后,我需要使用 Java 获取数组并能够检索这些标志。这可能看起来像:

somevar array = array_from_php;
if(array[0][flag3] == 1)//Player has unlocked this flag
/*do something */

非常感谢任何建议。

最佳答案

我认为你不需要一个数组,而是一个字节(8位)或要存储的字(16 位)或双字(32 位)您的标志位于 RAM 中或持久存在于数据库或文本文件中。

虽然 PHP 不是一种类型保存语言,但据我所知,您无法声明这些类型。但你启发了我。 PHP的error_reporting值是这样存储的。但我认为它是一个完整的整数,而不仅仅是一个字节、字或双字。

我做了一些测试,它似乎有效:

<?php

// Flag definitions
$defs = array(
"opt1" => 1,
"opt2" => 2,
"opt3" => 4,
"opt4" => 8,
"opt5" => 16,
"opt6" => 32
);

// enable flag 1,3 and 4 by using a bitwise "OR" Operator
$test = $defs["opt1"] | $defs["opt3"] | $defs["opt4"];
displayFlags($test, $defs);

// enable flag 6, too
$test |= $defs["opt6"];
displayFlags($test, $defs);

// disable flag 3
$test &= ~$defs["opt3"];
displayFlags($test, $defs);

// little improvement: the enableFlag/disableFlag functions
enableFlag($test, $defs["opt5"]);
displayFlags($test, $defs);

disableFlag($test, $defs["opt5"]);
displayFlags($test, $defs);

function displayFlags($storage, $defs) {

echo "The current storage value is: ".$storage;
echo "<br />";

foreach($defs as $k => $v) {
$isset = (($storage & $v) === $v);
echo "Flag \"$k\" : ". (($isset)?"Yes":"No");
echo "<br />";
}

echo "<br />";
}

function enableFlag(&$storage, $def) {
$storage |= $def;
}

function disableFlag(&$storage, $def) {
$storage &= ~$def;
}

输出为:

The current storage value is: 13
Flag "opt1" : Yes
Flag "opt2" : No
Flag "opt3" : Yes
Flag "opt4" : Yes
Flag "opt5" : No
Flag "opt6" : No

The current storage value is: 45
Flag "opt1" : Yes
Flag "opt2" : No
Flag "opt3" : Yes
Flag "opt4" : Yes
Flag "opt5" : No
Flag "opt6" : Yes

The current storage value is: 41
Flag "opt1" : Yes
Flag "opt2" : No
Flag "opt3" : No
Flag "opt4" : Yes
Flag "opt5" : No
Flag "opt6" : Yes

The current storage value is: 57
Flag "opt1" : Yes
Flag "opt2" : No
Flag "opt3" : No
Flag "opt4" : Yes
Flag "opt5" : Yes
Flag "opt6" : Yes

The current storage value is: 41
Flag "opt1" : Yes
Flag "opt2" : No
Flag "opt3" : No
Flag "opt4" : Yes
Flag "opt5" : No
Flag "opt6" : Yes

结论:

我认为这是用最小空间存储标志的最有效方法。但是,如果您将其像这样存储在数据库中,则可能会在对这些标志进行有效查询时遇到问题。我认为不可能查询整数值的一个或多个特定位。但也许我错了,您也可以在查询中使用按位运算符。不过,我喜欢这种保存数据的方式。

关于java - 添加到数组的最小可能值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373120/

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