C&放大器; PHP:使用位运算符整数保存设置? [英] C & PHP: Storing settings in an integer using bitwise operators?

查看:135
本文介绍了C&放大器; PHP:使用位运算符整数保存设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉位运算符,但我似乎他们使用之前储存简单的设置。

I'm not familiar with bitwise operators, but I have seem them used to store simple settings before.

我需要通过开启/关闭选项功能好几了,我想用这个一个整数。我该如何去设置和读取这些选项?

I need to pass several on/off options to a function, and I'd like to use a single integer for this. How can I go about setting and reading these options?

推荐答案

您肯定能做到这一点在PHP。

You sure can do it in PHP.

比方说,你有你想要在一个单一的值存储4个布尔值。这意味着我们需要的存储空间四位

Let's say you have four booleans you want to store in a single value. That means we need four bits of storage space

0000

每个位,单独设置的时候,有小数独特的重新presentation

Each bit, when set individually, has a unique representation in decimal

0001 = 1 // or 2^0
0010 = 2 // or 2^1
0100 = 4 // or 2^2
1000 = 8 // or 2^3

要实现一个常见的​​方法是使用位掩码重新present每个选项。 PHP的错误级别完成这种方式,例如。

A common way to implement this is with bit masks to represent each option. PHP's error levels are done this way, for example.

define( 'OPT_1', 1 );
define( 'OPT_2', 2 );
define( 'OPT_3', 4 );
define( 'OPT_4', 8 );

然后,当你有一个重新presents 0以上这些标志的整数,你检查与按位和操作是&安培;

$options = bindec( '0101' );
// can also be set like this
// $options = OPT_1 | OPT_3;

if ( $options & OPT_3 )
{
  // option 3 is enabled
}

此操作符这样:只有在两个操作数设置的结果设置位

This operator works as such: only bits that are set in both operands are set in the result

0101 // our options
0100 // the value of OPT_3
----
0100 // The decimal integer 4 evaluates as "true" in an expression

如果我们检查了它反对 OPT_2 ,那么结果会是这样。

If we checked it against OPT_2, then the result would look like this

0101 // our options
0010 // the value of OPT_2
----
0000 // The decimal integer 0 evaluates as "false" in an expression

这篇关于C&放大器; PHP:使用位运算符整数保存设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆