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

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

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)
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值