Home  >  Q&A  >  body text

python - 按位“与”、“或”、“异或”运算的使用场景有什么?

按位“与”、“或”、“异或”运算的使用场景有什么?

阿神阿神2742 days ago910

reply all(5)I'll reply

  • 阿神

    阿神2017-04-17 18:02:22

    XOR operation is one of the core operations of cryptography.

    Many symmetric encryptions are based on XOR operations.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 18:02:22

    They are all binary operators, and they are assembly concepts. Generally speaking, they are not used.
    But because they are relatively low-level operators, the calculation speed is very fast, and they can also be used in regular operations.
    For example:
    The AND operator is generally used to clear.
    The AND operator can be used to convert an integer to a short integer (actually converting dword to word).

    0xffffeeee&0xffff=0xeeee

    Or operation is generally used to complement codes.
    For example, an integer type is 4 bytes and 32 bits, which means that it can be configured to accommodate 32 bits. (TRUE/FALSE),这个时候可以用Come and set a certain position to 1.

    Exclusive OR is generally used for encryption
    In addition, there are other oddities such as left shift for multiplication and right shift for division.

    There are too many knowledge points in this area, and generally there is no need to study it specially. If you know more about binary, you will understand it. To be honest, it is quite difficult.
    I typed for a long time, but I guess not many people could understand it. .

    reply
    0
  • PHPz

    PHPz2017-04-17 18:02:22

    Bit operations are used more in embedded and driver programming. They are used when directly operating registers. It seems that there are not many in the application layer.
    However, I have the impression that there are many strange techniques that can be used. The one that impressed me most is a question on leetcode:
    LeetCode 136. Single Number

    The question is very simple. The requirement is to find the only integer that appears once in the array, while the others will appear twice.

    The usual idea is to create a table, but when the array is large, the speed is very slow, and then there is the bitwise XOR algorithm.
    Directly XOR all the numbers in the array bitwise, and the last remaining number is what you want. As for why, you can search online.

    reply
    0
  • 黄舟

    黄舟2017-04-17 18:02:22

    Let’s take an example from a real scenario
    Configure the value of certain bits in a byte.
    Example:
    To set a certain bit of this variable, use bitwise OR a = a|0x01, which sets the last bit. To extract the value of a certain bit, you can use bitwise AND b = a&0x01, which is the extraction The value of the last digit.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 18:02:22

    • Bitmask, bitmap, etc.

    • Binary format processing (e.g. TCP header)

    • Cryptography

    reply
    0
  • Cancelreply