首页 技术 正文
技术 2022年11月19日
0 收藏 859 点赞 2,274 浏览 1354 个字

操作系统 : CentOS7.3.1611_x64

gcc版本 :4.8.5

Python 版本 : 2.7.5

思路如下 :

1、将浮点数a通过内存拷贝,赋值给相同字节的整型数据b;

2、将b转换为网络字节序变量c并发送到服务端;

3、服务端接收c并将c转换为主机字节序变量d;

4、将整型数据d通过内存拷贝,赋值给相同字节的浮点数据e;

至此,浮点数网络传输完成。

C示例代码:

#define htonl64 htobe64
#define ntohl64 be64tohuint64_t htonf64(double dvalue)
{
uint64_t ulltmp = 0;
memcpy(&ulltmp,&dvalue,8);
ulltmp = htonl64(ulltmp);
return ulltmp;
}double ntohf64(uint64_t ulvalue)
{
uint64_t ulltmp = 0;
double ret = 0.0;
ulltmp = ntohl64(ulvalue);
memcpy(&ret,&ulltmp,8);
return ret;
}

  完整示例代码如下:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <endian.h>/*
double类型数据网络字节序与主机字节序之间的转换
*/#define htonl64 htobe64
#define ntohl64 be64tohuint64_t htonf64(double dvalue)
{
uint64_t ulltmp = 0;
memcpy(&ulltmp,&dvalue,8);
ulltmp = htonl64(ulltmp);
return ulltmp;
}double ntohf64(uint64_t ulvalue)
{
uint64_t ulltmp = 0;
double ret = 0.0;
ulltmp = ntohl64(ulvalue);
memcpy(&ret,&ulltmp,8);
return ret;
}int main()
{
double a = 123.456;
uint64_t b = 0;
double c = 0.0;
printf("a = %lf\n",a);
b = htonf64(a);
printf("b = %ld\n",b);
c = ntohf64(b);
printf("c = %lf\n",c);
return 0;
}

  python示例代码 :

def htonfl(f):
s = struct.pack('d',f)
return struct.unpack('!Q',s)[0]def fltonl(v):
s = struct.pack('!Q',v)
return struct.unpack('d',s)[0]

  完整代码:

#! /usr/bin/env python
# -*- coding:utf-8 -*-import structdef htonfl(f):
s = struct.pack('d',f)
return struct.unpack('!Q',s)[0]def fltonl(v):
s = struct.pack('!Q',v)
return struct.unpack('d',s)[0]a = 123.456
print a
b = htonfl(a)
print b , hex(b)
print fltonl(b)

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919