Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

php - When should I use a bitwise operator?

I read the following Stack Overflow questions, and I understand the differences between bitwise and logical.

However, none of them explains when I should use bitwise or logical.

When should I use bitwise operators rather than logical ones and vice versa?

In which situation do I need to compare bit by bit?

I am not asking about the differences, but I am asking the situation when you need to use bitwise operators.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bitwise is useful for things in PHP just like anything else.

How about a value that can have multiple states turned on at the same time?

<?php

// since we're setting constant values in base10 we must progressively double
// them since bitwise operations work in base2. you'll see why when we output
// these as binary values below.
const STATE_FOO = 1;
const STATE_BAR = 2;
const STATE_FEZ = 4;
const STATE_BAZ = 8;

// show base2 values of the above constants
echo sprintf("STATE_FOO's base2 value is %08d
", decbin(STATE_FOO));
echo sprintf("STATE_BAR's base2 value is %08d
", decbin(STATE_BAR));
echo sprintf("STATE_FEZ's base2 value is %08d
", decbin(STATE_FEZ));
echo sprintf("STATE_BAZ's base2 value is %08d

", decbin(STATE_BAZ));

// set state to FOO and FEZ
$state = STATE_FOO | STATE_FEZ;

echo sprintf("base10 value of $state is %s
", $state);
echo sprintf("base2 value of $state is %08d
", decbin($state));
echo sprintf("Does $state include FOO state? %s
", (bool)($state & STATE_FOO));
echo sprintf("Does $state include BAR state? %s
", (bool)($state & STATE_BAR));
echo sprintf("Does $state include FEZ state? %s
", (bool)($state & STATE_FEZ));
echo sprintf("Does $state include BAZ state? %s
", (bool)($state & STATE_BAZ));
echo sprintf("Is state equivalent to FOO and FEZ states? %s
", ($state == (STATE_FOO | STATE_FEZ)));

Output:

STATE_FOO's base2 value is 00000001
STATE_BAR's base2 value is 00000010
STATE_FEZ's base2 value is 00000100
STATE_BAZ's base2 value is 00001000

base10 value of $state is 5
base2 value of $state is 00000101
Does $state include FOO state? 1
Does $state include BAR state?
Does $state include FEZ state? 1
Does $state include BAZ state?
Is state equivalent to FOO and FEZ states? 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...