Python实现IEEE754数据十六进值数与浮点数的转换 带socket加密传输的实例

  • Post author:
  • Post category:python




十六进制数据转换为对应的浮点数

python2的版本

import struct

def learn_to_pack_func():
    ''
    while(1):
        op_id = int(raw_input('please select float to hex(0) or hex to float(1),other value to quit:'))
        if op_id == 0:
            num = float(raw_input('please input the float number:'))    #输入浮点数转换为16进制
            result = struct.pack('>f',num).encode('hex')
            print result
        elif op_id== 1:
            num =str(raw_input('please input the hex number:'))         #输入十六进制数装换为浮点数
            str1= num[2:]
            str2 =struct.unpack('>f',(str1.decode('hex')))
            print str2
        else:
            break
    return 0
    
learn_to_pack_func()

输出:

please select float to hex(0) or hex to float(1),other value to quit:0
please input the float number:16.0
41800000
please select float to hex(0) or hex to float(1),other value to quit:1
please input the hex number:0x41800000
41800000
(16.0,)
please select float to hex(0) or hex to float(1),other value to quit:5

python3版本

import struct
import ctypes

#两种不同的模块来解析
def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])
def float2hex(s):
    fp = ctypes.pointer(ctypes.c_float(s))
    cp = ctypes.cast(fp,ctypes.POINTER(ctypes.c_long))
    return hex(cp.contents.value)

def hex_to_float(h):
    i = int(h,16)
    return struct.unpack('<f',struct.pack('<I', i))[0]
def hex2float(h):
    i = int(h,16)
    cp = ctypes.pointer(ctypes.c_int(i))
    fp = ctypes.cast(cp,ctypes.POINTER(ctypes.c_float))
    return fp.contents.value
    
print(hex_to_float("0x41800000"))
print(hex2float("0x41800000"))
print(float2hex(16.0))
print(float_to_hex(16.0))

输出

16.0
16.0
0x41800000
0x41800000

使用socket 传输数据 使用struct加密传输

import socket
import struct

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(('127.0.0.1', 6666))
a = (0x41800000)
s = struct.Struct('<i')
qwe = s.pack(*a)
sock.send(qwe)

接收并解密为浮点数(伪代码)

import struct
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock_port = int(conf.get("war_socket", "host"))
sock_ip = conf.get("war_socket", "ip")
sock.bind((sock_ip, sock_port))      #绑定IP地址和端口号  自己写端口
buf, send_address = sock.recvfrom(4096)

def ieefloat(self, buf):
    #特殊浮点数转换
    s = struct.Struct('<i')        
    iee = s.unpack(f)
    packed_data = struct.unpack('<f', struct.pack('<I', int(hex(int(iee[0])), 16)))
    return packed_data[0]
 
ieefloat(buf)



版权声明:本文为weixin_42784553原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。