I’m currently taking geek Time, a math 101 for programmers.

Courses address: time.geekbang.org/column/intr…

This is the study note for the first lecture, on base conversion.


binary

What is binary

Decimal counting is using 10 as the base, such as a number: 2871, which is expressed in decimal, i.e


Binary takes 2 as its base, and its digits areIn the form. For example, binary numbers110101, it is converted to decimal representation as follows:


In this vein, the same goes for octal (base 8) and hexadecimal (base 16), as well as decimal conversions.

Convert binary to decimal using Python code, as shown below:

# decimal to binary method: in addition to take more than 2, the reverse arrangement, https://blog.csdn.net/shirley_sweet/article/details/73896279
def change(n):
    result = '0'
    if n == 0:  # if input is 0
        return result
    else:
        result = change(n // 2)  # call itself
        return result + str(n % 2)

def decimal_to_binary(decimal_val):
    Decimal to binary :param decimal_val: :return: ""
    print('transfer %d to binary' % decimal_val)
    recursion_result = change(decimal_val)
    print('Recursive implementation of the conversion result:', recursion_result)

def binary_to_decimal_func(val):
    "Is implemented by definition, of the form 2^n :param val: STR :return:"
    print('original val: ', val)
    numbers = len(val)
    result = 0
    for i in range(numbers):
        result += int(val[i]) * pow(2, numbers - i - 1)
    return result


def binary_to_decimal(val):
    Binary to decimal :param val: :return: ""
    decimal2 = binary_to_decimal_func(str(val))
    print('Second way to convert binary to decimal:', decimal2)
Copy the code

In fact, Python has built-in functions to convert directly between these bases. For example, bin, OCT, and HEX stand for converting decimal numbers to binary, octal, and hexadecimal, respectively. The int(val, base) function can be used to convert other bases to decimal. The input value val must be a string, and the base argument is set to the base used for the current input value, such as binary base=2.

def binary_to_decimal(val):
    Binary to decimal :param val: :return: ""
    The first method, the built-in function int(), must be a string
    decimal = int(str(val), 2)
    print('Binary number: 0b%d' % val)
    print('Convert binary to decimal to:', decimal)
    
def decimal_to_other_build_function(dec):
    "' using built-in functions to convert decimal reference http://www.runoob.com/python3/python3-conversion-binary-octal-hexadecimal.html: param dec: : return: ' ' '
    print("The decimal number is:", dec)
    print("Convert to binary to:", bin(dec))
    print("Convert to octal:", oct(dec))
    print("Convert to hexadecimal:", hex(dec))
Copy the code

Why do computers use binary?

  1. Binary data expression has the advantages of strong anti-interference ability and high reliability.
  2. Binary is great for logical operations;
  3. The logic circuit that makes up a computer system usually has only two states, namely switch on and switch off.

Binary bit operations

Shift operation

If the binary is moved one bit to the left, it means that the number is doubled, that is, multiplied by 2. However, if the binary is moved one bit to the left, it needs to pay attention to the problem of number overflow. It needs to consider the number of digits of the variable type currently used, such as int16 type, that is, only 16 digits, then it needs to consider whether the number of digits of the current value reaches 16 digits.

If the binary is moved one bit to the right, the number is divided by 2, and the integer quotient is used. Note that the right shift is divided into arithmetic right shift and sign right shift, because of the sign bit. In general, the sign bit is 0, indicating that the value is positive. The sign bit is 1, indicating that the value is negative.

For logical right shift, need to fill in the left side of the sign bit after the right shift, that is, positive complement 0, negative complement 1;

For arithmetic right shift, you leave the sign bit unchanged and move the rest of the digits right.

In the Java language, logical right-shifts are represented by >>> and arithmetic right-shifts are represented by >>, but Python does not have >>> operators to implement logical right-shifts.

Simple implementation of left shift operation and arithmetic right shift operation:

def left_shift(val, n):
    Left shift operation :param val: :param n: number of digits moved :return: ""

    print('Binary number: 0b%d' % val)
    val = int(str(val), 2)
    print('Decimal values:', val)
    result = val << n
    print('left shift %d, result=%s' % (n, result))
    result = bin(int(result))
    print('left shift {}, result={}'.format(n, result))

def right_shift(val, n):
    Param val: :param n: :return: ""
    print('Binary number: 0b%d' % val)
    val = int(str(val), 2)
    print('Decimal values:', val)
    math_val = val >> n
    print('right shift {}, math_val={}'.format(n, math_val))
    result = bin(int(math_val))
    print('left shift {}, result={}'.format(n, result))
Copy the code

The test code is as follows:

binary_val = 100101
The output is 0b1001010
left_shift(binary_val, 1)
The output is 0b10010
right_shift(binary_val, 1)
Copy the code
Logical operations
  • Or: as long as one of the bits is 1, the final result is 1;
  • And: The bits involved in the operation must all be 1, the final result is 1, otherwise it is 0;
  • Xor: The result is 0 if the bits involved are the same, or 1 if not.

The code implementation is as follows:

def logic_operation(val1, val2):
    Binary logical operations, and, or, not, and xor operations :param val1: :param val2: :return:"
    print('orginal val:{},{}'.format(val1, val2))
    dec_val1 = int(str(val1), 2)
    dec_val2 = int(str(val2), 2)
    print('decimal val:{},{}'.format(dec_val1, dec_val2))
    and_result = dec_val1 & dec_val2
    or_result = dec_val1 | dec_val2
    not_result1 = ~dec_val1
    not_result2 = ~dec_val2
    different_or_result = dec_val1 ^ dec_val2
    print('and the result:, bin(int(and_result)))
    print('or result:, bin(int(or_result)))
    print('not result1:', bin(int(not_result1)))
    print('not result2:', bin(int(not_result2)))
    print('different or result:', bin(int(different_or_result)))

if __name__ == '__main__':
    binary_val = 100101
    binary_val2 = 110100
    logic_operation(binary_val, binary_val2)
Copy the code

The two binary values tested are 100101 and 110100, and the output is as follows, where the operation of not is reversed by bit, and for signed numbers, positive numbers become negative.

orginal val:100101.110100
decimal val:37.52
andThe result:0b100100
orThe result:0b110101
notResult1:0b100110
notResult2:0b110101
different orThe result:0b10001
Copy the code

The address of the source code above is:

Github.com/ccc013/Code…


Welcome to follow my wechat official account – Machine Learning and Computer Vision, or scan the qr code below, we can communicate, learn and progress together!