运算符二进制_基本转换和二进制运算符

运算符二进制

This article discusses PHP’s binary operators and how to convert between different counting systems. Most programming books and articles only dedicate a page or two to such topics, and although using the operators is really quite simple, there’s a fair amount of background knowledge one must have to use them correctly.

本文讨论PHP的二进制运算符以及如何在不同的计数系统之间进行转换。 大多数编程书籍和文章仅将一两个页面专门用于此类主题,尽管使用运算符确实非常简单,但是要正确使用它们,必须有大量的背景知识。

Instead of giving the same bare-bones treatment that every other reference gives, I’ll first provide you the necessary background in number theory. Armed with that knowledge, you’ll be able to understand the binary counting system and base conversions… and familiarity with binary digits is the key to successful use of the binary operators! So without further delay, let’s get started!

我将首先为您提供数论的必要背景,而不是像其他参考文献那样给予相同的准系统处理。 有了这些知识,您就可以了解二进制计数系统和基本转换……熟悉二进制数字是成功使用二进制运算符的关键! 因此,不用再拖延了,让我们开始吧!

数论 (Number Theory)

The counting system with which we’re all familiar can be thought of as a series of packages and containers. Each package is worth one unit and is bundled together with other packages and placed in an appropriate container. Each container can only hold a certain amount of units and the units must be packaged into proper packages for that container.

我们都熟悉的计数系统可以认为是一系列包装和容器。 每个包装物价值一个单位,并与其他包装物捆在一起,放在适当的容器中。 每个容器只能容纳一定数量的单元,并且必须将这些单元包装到该容器的适当包装中。

In our Base-10 counting system, units are bound together in multiples of 10. That means we can have up to nine single units, but once a 10th unit is added they all must be packaged together to make a single bundle.

在我们的Base-10计数系统中,单位以10的倍数绑定在一起。这意味着我们最多可以有9个单位,但是一旦添加了第10个单位,则必须将它们全部打包在一起以形成一个捆绑包。

Base Converting and Binary Operators 1

There are no surprises there, but the magic lies within the containers. Let’s place a series of buckets side by side and restrict ourselves to filling only the right-most containers. Once one bucket is full, its units are bundled up and moved to the neighboring container. That is, the right-most container can only hold nine single units. A 10th unit would be bundled with the first nine and the whole bundle is moved to the container to its left.

毫无意外,但魔力在于容器内。 让我们并排放置一系列水桶,并限制自己只能装满最右边的容器。 一旦一个桶装满了,就将其装箱并捆绑到附近的容器中。 即,最右边的容器只能容纳9个单个单元。 将第10个单元与前9个单元捆绑在一起,然后将整个捆绑包移到左侧的容器中。

Base Converting and Binary Operators 2

Each container can only hold nine of whatever size packages it holds. The right-most container can only hold nine units before they get bundled. The container to its left can only hold 9 bundles. A 10th bundle gets rebundled together and moved the neighboring container. As the containers continue to fill up, the cycle repeats itself; the container to the left can always hold nine bundles of whatever the right container can hold.

每个容器只能容纳九个其容纳的任何尺寸的包装。 最右边的容器在捆扎之前只能容纳九个单元。 左侧的容器只能容纳9个捆。 第10捆捆绑在一起,并移动了相邻的容器。 当容器继续装满时,该循环重复进行。 左侧的容器始终可以容纳九捆正确的容器可以容纳的捆。

The base-10 counting system we’re most familiar with is called decimal, but other counting systems exist. The key is that the limit of each container is one less that of the base. For example, the limit of each container in an octal counting system (base-8) is 7. In hexadecimal (base-16), each container holds 15 units. In hexadecimal, the letters A through F are often used to represent the quantities 10 through 15.

我们最熟悉的以10为底的计数系统称为十进制,但也存在其他计数系统。 关键是每个容器的限制要比基数少一。 例如,八进制计数系统(基数8)中每个容器的限制为7。在十六进制(基数16)中,每个容器可容纳15个单位。 在十六进制中,字母A到F通常用于表示数量10到15。

In binary (base-2) each container is limited to one unit or bundle.

在二进制(以2为底)中,每个容器仅限于一个单位或一捆。

Base Converting and Binary Operators 3

Since each container is limited to one unit or bundle, a value that makes up a binary number can only be a one or a zero. It is either full (a value of one) or empty (a value of zero). When the string of container values is written out it can resemble a series of checkmarks as if on a list: 1 can be considered a checkmark and 0 is the absence of a check.

由于每个容器仅限于一个单位或成捆,组成二进制数的值只能是1或0。 它是完整的(值为1)或为空的(值为0)。 当写出容器值字符串时,它可能类似于一系列选中标记,就好像在列表上一样:1可以视为选中标记,而0则表示没有选中。

Base Converting and Binary Operators 4

转换功能 (Conversion Functions)

Converting values from one base to another can be tedious if done manually depending on the size of the value. To help make life easier, PHP has several built-in functions which can be used for the conversion of numbers from one base to another: decbin(), bindec(), decoct(), octdec(), dechex(), hexdec(), and base_convert().

如果根据值的大小手动进行,则将值从一个基数转换为另一基数可能很繁琐。 为了使生活更轻松,PHP具有一些内置函数,可用于将数字从一个基数转换为另一个基数: decbin()bindec() decoct()octdec()dechex()hexdec() dechex()hexdec()base_convert()

The decbin() function accepts a decimal format number and returns a string representing the binary equivalent. The counterpart function bindec() accepts a string representing a binary number and returns the decimal value.

decbin()函数接受十进制格式的数字,并返回表示二进制等效项的字符串。 对应函数bindec()接受代表二进制数的字符串,并返回十进制值。

The decoct() function accepts a decimal format number and returns a string representing its octal equivalent. Its counterpart octdec() accepts the string representation of an octal value and returns the decimal number.

decoct()函数接受十进制格式的数字,并返回表示其八进制等效形式的字符串。 其对应的octdec()接受八进制值的字符串表示形式,并返回十进制数。

dechex() accepts a decimal value and returns a string representation of the hexadecimal value; hexdec() accepts a string representing a hexadecimal number and returns the decimal equivalent.

dechex()接受一个十进制值,并返回一个十六进制值的字符串表示形式; hexdec()接受表示十六进制数字的字符串,并返回等效的十进制数。

<?php
$num = 21;

echo "Decimal value: $numn";

echo "Binary value: " . decbin($num) . "n";
echo "Octal value: " . decoct($num) . "n";
echo "Hexadecimal value: " . dechex($num) . "n";

In the code above, a decimal value of 21 is stored in the variable $num. The functions decbin(), decoct(), and dechex() are used to display the binary, octal, and hexadecimal equivalents; the binary value is 10101, the octal value is 25, and the hexadecimal value is 15.

在上面的代码中,十进制值21存储在变量$num 。 功能decbin() decoct()dechex()被用于显示二进制,八进制,十六进制和等同物; 二进制值为10101,八进制值为25,十六进制值为15。

The base_convert() function is used to convert between arbitrary bases. It accepts two arguments, the first is the original base and the second is the desired base. Let’s assume a particular program needs to convert base-7 and base-11 values; there are no convenience functions to perform these tasks, so base_convert() is used.

base_convert()函数用于在任意基数之间进行转换。 它接受两个参数,第一个是原始基准,第二个是所需基准。 假设特定程序需要转换base-7和base-11值; 没有方便的功能来执行这些任务,因此使用base_convert()

<?php
$num = 21;

echo "Decimal value: $numn";

echo "Base-7 value: " . base_convert($num, 10, 7) . "n";
echo "Base-11 value: " . base_convert($num, 10, 11) . "n";

The base-7 value of decimal 21 is 30, and base-11 is 1A.

十进制21的base-7值为30,base-11为1A。

Granted, base-7 and base-11 certainly seem strange, but they do illustrate how base_convert() works. Perhaps more realistically you’ll find yourself using base_convert() to convert directly between binary, octal, and hexadecimal values when a convenience function isn’t available.

当然,base-7和base-11看起来很奇怪,但是它们确实说明了base_convert()工作方式。 也许更现实的是,当便捷功能不可用时,您会发现使用base_convert()直接在二进制,八进制和十六进制值之间进行转换。

<?php
$octNum = 25;

echo "Octal value: $octNumn";
echo "Binary value: " . base_convert($octNum, 8, 2) . "n";

按位运算符 (Bitwise Operators)

Back in the number theory section you saw that each binary container could either be full (have a value of one) or empty (a value of zero). Each package that fills a container we call a “bit”.

回到数字理论部分,您看到每个二进制容器可以是满的(值为1)或为空的(值为0)。 每个填充容器的包装都称为“位”。

按位与 (Bitwise-And)

The bitwise-and operator is an ampersand (&). It accepts two values and logically ands their binary values. Consider the following example:

按位与运算符是“& & 。 它接受两个值,并在逻辑上将它们的二进制值相加。 考虑以下示例:

Base Converting and Binary Operators 5

The bitwise-and operation takes the binary representation of two numbers and returns a number constructed based on which fields both hav a value of 1. 5 & 3 = 1 since both binary representations only have a 1 value in the right most location.

按位与运算采用两个数字的二进制表示形式,并返回一个基于其构造的数字,该两个字段的值均为1。5&3 = 1,因为两个二进制表示形式在最右边的位置仅具有1值。

按位或 (Bitwise-Or)

The bitwise-or operator is a pipe (|). It accepts two values and logically ors their binary values.

按位或运算符是管道( | )。 它接受两个值,并在逻辑上或它们的二进制值。

Base Converting and Binary Operators 6

The bitwise-or operation takes the binary representation of two number and returns a number constructed based on which fields at least one of have a value of 1. 5 | 3 = 7 since between the two binary representations have a 1 value in each location.

按位或运算采用两个数字的二进制表示形式,并返回一个数字,基于该数字构造的至少一个字段的值为1。5 | 3 = 7,因为两个二进制表示之间的每个位置的值均为1。

按位异或(XOR) (Bitwise-Exclusive Or (XOR))

The bitwise-xor operator is a caret (^). In contrast to the bitwise-or where a 1 is returned for a particular bit so long as at least one of the bits is set, the bitwise-xor will only return one if only one of the bits are set.

按位异或运算符是插入符号( ^ )。 与按位或特定位返回1的情况相反,只要设置了至少一位,按位异或运算仅在设置了位中的一个时才返回1。

Base Converting and Binary Operators 7

The bitwise-xor will only return one if only one of the bits are set. If neither of the bits are set, or if both bits are set, zero will be returned. 5 ^ 3 = 6.

如果仅设置了一位,则按位异或将仅返回1。 如果两个位都没有置位,或者两个位都置位,则将返回零。 5 ^ 3 = 6。

按位称赞 (Bitwise Compliment)

The compliment operator is a tilde (~). It flips the bits in a value so that positions that were 1 would then be 0, and positions that were zero would then be 1.

称赞运算符是波浪号( ~ )。 它翻转值中的位,以使位置为1的位置为0,位置为零的位置为1。

Base Converting and Binary Operators 8

Since the compliment switches the values of bits from 1 to 0 and from 0 to 1 in the binary representation of a value, ~5 = 2.

由于补码将值的二进制表示形式中的位值从1切换为0,将值从0切换为1,因此〜5 = 2。

用二元运算符屏蔽 (Masking with Binary Operators)

We also briefly saw earlier how binary numbers can be used as a type of checklist; PHP’s bitwise operators can prove helpful in manipulating and masking these tallies by working with each bit.

前面我们还简要地介绍了如何将二进制数用作一种清单。 PHP的按位运算符可以通过处理每个位来帮助操纵和掩盖这些计数。

<?php
// people and values from previous chart
$people = array(
    "Joe" => 3,
    "Ned" => 20,
    "Sally" => 14
);

// mask values if person has certain animal
$mask = array(
    "rabbit" => bindec("00001"),
    "dog" => bindec("00010"),
    "cat" => bindec("00100"),
    "bird" => bindec("01000"),
    "snake" => bindec("10000")
);

foreach ($people as $person => $value) {
    // who has a pet dog?
    if (($value & $mask["dog"]) == $mask["dog"]) {
        echo "$person has a dog.n";
    }
    // who has a snake
    if (($value & $mask["snake"]) == $mask["snake"]) {
        echo "$person has a snake.n";
    }
    // who does NOT have a cat?
    if ((~$value & $mask["cat"] ) == $mask["cat"]) {
        echo "$person does not have a cat.n";
    }
    // who has both a cat and a bird?
    if (($value & $mask["cat"] + $mask["bird"]) == $mask["cat"] + $mask["bird"]) {
        echo "$person has both a cat and a bird.n";
    }
}

The example assigns the data from the pet survey chart you saw earlier into an array with the name $people. A mask value is then assigned for each animal based on its position in the survey chart. The resulting binary string is converted to a decimal number using bindec(). The values are stored in the array $mask.

该示例将您先前看到的宠物调查图表中的数据分配到名为$ people的数组中。 然后根据每个动物在调查图中的位置为其分配一个掩码值。 使用bindec()将所得的二进制字符串转换为十进制数。 这些值存储在数组$ mask中。

A foreach loop cycles through each element person and tests for various conditions we’ve set. Each condition uses binary operators to mask out the values we don’t want. If the isolated value matches the value of the mask, it means the survey results matches the criteria we’re looking for. It’s important watch the order of operations though and use parenthesis to ensure the operators work on the correct data.

foreach循环遍历每个元素人并测试我们设置的各种条件。 每个条件都使用二进制运算符来掩盖我们不想要的值。 如果隔离的值与掩码的值匹配,则意味着调查结果与我们正在寻找的标准匹配。 重要的是要注意操作顺序,并使用括号确保操作员处理正确的数据。

摘要 (Summary)

This article definitely covered a lot of material! I provided you with a look at how counting systems are structured, showed you how to convert between various number system, and then how to use binary operators. The article concluded with a simple bit-masking example to pull everything together. Hopefully now you’ll be able to successfully incorporate these seemingly tricky concepts in your scripts with ease!

这篇文章肯定涵盖了很多内容! 我向您介绍了计数系统的结构,向您展示了如何在各种数字系统之间进行转换,以及如何使用二进制运算符。 本文以一个简单的位屏蔽示例结束,将所有内容整合在一起。 希望现在您能够轻松地将这些看似棘手的概念成功地合并到脚本中!

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/base-converting-and-binary-operators/

运算符二进制

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值