Python read byte value of a bit, the value of a bit set, bit operations

Python read byte value of a bit, the value of a bit set, bit operations

  In practice things development project, in order to improve performance, the mating end of the device, is often used is the protocol for encapsulation of the binary string of bytes embodiment, will be more and 0 1, True and False, Yes and No such every eight Boolean only occupies one byte, the byte with the bits. Reduce the volume, to reduce the requirements for stability of the network. This brings to how to read a byte value in each and every issue and how to set the value of each bit.

  These days training presentations write the code, by the way wrote two functions, solve byte bit value literacy problems, now for everyone to share.

  Directly following the code on the test Python3 by:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def get_bit_val(byte, index):
    """
    得到某个字节中某一位(Bit)的值

    :param byte: 待取值的字节值
    :param index: 待读取位的序号,从右向左0开始,0-7为一个完整字节的8个位
    :returns: 返回读取该位的值,0或1
    """
    if byte & (1 << index):
        return 1
    else:
        return 0


def set_bit_val(byte, index, val):
    """
    更改某个字节中某一位(Bit)的值

    :param byte: 准备更改的字节原值
    :param index: 待更改位的序号,从右向左0开始,0-7为一个完整字节的8个位
    :param val: 目标位预更改的值,0或1
    :returns: 返回更改后字节的值
    """
    if val:
        return byte | (1 << index)
    else:
        return byte & ~(1 << index)


print(get_bit_val(3, 2))        # 3的2进制00000 0 11,2号位是0,打印结果0
print(get_bit_val(3, 1))        # 3的2进制000000 1 1,1号位是1,打印结果1
print(get_bit_val(3, 5))        # 3的2进制00 0 00011,5号位是0,打印结果0

print(set_bit_val(3, 2, 1))     # 3的2进制00000 0 11,2号位改成1,打印结果7(00000111)
print(set_bit_val(3, 1, 0))     # 3的2进制000000 1 1,1号位改成0,打印结果1(00000001)
print(set_bit_val(3, 5, 0))     # 3的2进制00 0 00011,5号位改成0,打印结果3(00000011)


"""
控制台输出:
0
1
0
7
1
3
"""

Guess you like

Origin www.cnblogs.com/xueweisuoyong/p/11874444.html
Bit
BIT