常用的函数,目前有下面几个,待增加
round_qsw(number,power=0)
intToFloat_qsw(v:int,tag=4)
floatToInt_qsw(v:float,tag=4)
checkSum_qsw(arg:str,byteorder='little')
hexToAsc_qsw(arg:str)
ascToHex_qsw(v:str)
def round_qsw(number,power=0):
"""
实现精确四舍五入,包含正、负小数多种场景
:param number: 需要四舍五入的小数
:param power: 四舍五入位数,支持0-∞
:return: 返回四舍五入后的结果
"""
digit = 10 ** power
num2 = float(int(number * digit))
# 处理正数,power不为0的情况
if number>=0 and power !=0:
tag = number * digit - num2 + 1 / (digit * 10)
if tag>=0.5:
return (num2+1)/digit
else:
return num2/digit
# 处理正数,power为0取整的情况
elif number>=0 and power==0 :
tag = number * digit - int(number)
if tag >= 0.5:
return (num2 + 1) / digit
else:
return num2 / digit
# 处理负数,power为0取整的情况
elif power==0 and number<0:
tag = number * digit - int(number)
if tag <= -0.5:
return (num2 - 1) / digit
else:
return num2 / digit
# 处理负数,power不为0的情况
else:
tag = number * digit - num2 - 1 / (digit * 10)
if tag <= -0.5:
return (num2-1)/digit
else:
return num2/digit
"""
实现求校验和功能
:par arg:字符串形式如‘00 01 02' 或 '000102' 必须是偶数位
"""
def checkSum_qsw(arg:str,byteorder='little'):
arg=arg.replace(" ","")
leng=len(arg)
if(leng%2!=0):
raise Exception("arg length is not even numbers!")
checksum=0
leng//=2
for i in range(0,leng):
t=arg[2*i:2*i+2]
#print(t)
x=int(t,16)
checksum +=x
checksum=checksum%256
return hex(checksum)
"""
实现转换浮点型内存格式
:par float:字符串形式如‘00 01 02' 或 '000102' 必须是偶数位
:par tat 几个字节 默认8个字节
:return 16进制格式
"""
def floatToInt_qsw(v:float,tag=4)->int:
import ctypes as c
_floatTYPE = c.c_double if tag is 8 else c.c_float
_intTYPE = c.c_ulonglong if tag is 8 else c.c_int
if isinstance(v,float):
v_float = _floatTYPE(v)
ptrTYPE = c.POINTER(_intTYPE)
ptr = c.cast(c.pointer(v_float),ptrTYPE)
return hex(ptr[0])
elif isinstance(v,int):
v_int = _intTYPE(v)
ptrTYPE = c.POINTER(_floatTYPE)
ptr = c.cast(c.pointer(v_int),ptrTYPE)
return hex(ptr[0])
else:
return hex(v)
"""
实现转换内存格式整型转浮点型 4个字节
:par float:字符串形式如‘00 01 02' 或 '000102' 必须是偶数位
:par tat 几个字节 默认4个字节
:return 16进制格式
"""
def intToFloat_qsw(v:int,tag=4):
import struct
ba=v.to_bytes(tag, byteorder='big', signed=True)
return struct.unpack("!f",ba)[0]
"""
字符串转16进制
quanshiwei = '7175616e736869776569'
"""
def ascToHex_qsw(v:str):
v=v.replace(" ","")
r=''
for tmp in v:
t=hex(ord(tmp))
r+=t[2:]
return r
"""
asc16进制转字符串
'7175616e736869776569' = quanshiwei
"""
def hexToAsc_qsw(arg:str):
arg=arg.replace(" ","")
leng=len(arg)
if(leng%2!=0):
raise Exception("arg length is not even numbers!")
checksum=''
leng//=2
for i in range(0,leng):
t=arg[2*i:2*i+2]
hexI=int(t,16)
x=chr(hexI)
checksum +=x
return checksum