Python学习:常用内建模块(2)struct,hashlib.md5

strcut模块用来处理bytes类型,可以将某个数据类型转换为byte,也可以将byte转换为指定类型.

这是把一个整数转换为4字节byte.

>>> n = 10240099
>>> b1 = (n & 0xff000000) >> 24
>>> b2 = (n & 0xff0000) >> 16
>>> b3 = (n & 0xff00) >> 8
>>> b4 = n & 0xff
>>> bs = bytes([b1, b2, b3, b4])
>>> bs
b'\x00\x9c@c'

用struct模块直接搞定

>>> import struct
>>> struct.pack('>I', 10240099)
b'\x00\x9c@c'

根据>IH的说明,后面的bytes依次变为I:4字节无符号整数和H:2字节无符号整数。

>>> struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')
(4042322160, 32896)

============================================================================

下面是利用hashlib模块写的一个注册类,可以注册且验证

import hashlib
class Register_Db(object):
    def __init__(self):
        self.__database = {}
    def register(self,username,password):
        if(username in self.__database):print('the username has been registered')
        else:self.__database[username] = self.cal_md5(password)
    def cal_md5(self,password):
        test = hashlib.md5()
        test.update(str(password).encode('utf-8'))
        return  test.hexdigest()
    def login(self,username,password):
        if(username in self.__database):
            if(self.__database[username] == self.cal_md5(password)):return True
            else: return False
        else:
            print('the user (%s) has not registered'%username)
            return False

R = Register_Db()
R.register('Mac','123456789')
R.register('Bob','ABCDEFG+++')
R.register('Moon','Liar_fuckiing')

print(R.login('Mac','123456789'),R.login('Moom','Liar_fuckiing'))

你可能感兴趣的:(Python学习:常用内建模块(2)struct,hashlib.md5)