|
最近在处理64位网络传输中遇到一些问题,下面是解决的一些过程和记录的笔记. ntoh64整个函数为前辈所写,在CSDN上查找到,对此表示感谢.
int64位在LINUX表示为 long long,有一种表示方式为int64,目前没有找到相关头文件和相关资料。
如果为网络传输。
第一种方法:当作字符串传输 第二种方法:linux在byteswap.h头文件里面提供了bswap_64这个宏,可以通过bswap_64来对字符顺序进行转换。
测试大小端字符序列 #include <stdio.h> #include <byteswap.h>
int main () { long long c = 0x1234567812345679;
long long d=bswap_64(c); //小端字符到大端字符 if (*(char *)&d == 0x12) printf ("Big endian\n"); else if (*(char *)&d == 0x79) printf ("Little endian\n");
//大端字符到小端字符 long long h=bswap_64(d); if (*(char *)&h == 0x12) printf ("Big endian\n"); else if (*(char *)&h == 0x79) printf ("Little endian\n"); return 0; }
Linux端传输到WINDOWS先转换为网络的大端字符序,代码如下: #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <byteswap.h> int main() { int fd; fd = open("file.txt", O_RDWR|O_CREAT|O_TRUNC); long long data = 135407575609; printf("%I64d\n", data); //cover big data = bswap_64(data); printf("%I64d\n", data); //write cover big write(fd, &data, sizeof(data)); printf("%I64d\n", data); data = 0; long long a; read(fd, &a, sizeof(a)); data = bswap_64(a); printf("%I64d\n", a);
close(fd); return 0; }
WINDOWS收到文件后根据需要看是否将网络的大端字符序转换为本地相应的字符序,代码如下: #include <stdio.h>
long long ntoh64(long long inval) { long long outval = 0; int i=0; for(i=0;i<8; i++) outval=(outval<<8)+ ((inval >> (i *8))&255); return outval; }
int main() { FILE *fp; fp = fopen("file.txt", "rb+"); long long buf=0; fread(&buf, sizeof(buf), 1, fp); printf("Read Data:%I64d\n", ntoh64(buf)); fclose(fp); return 0 ; }
测试结果 :可以正确读取他们的数据并显示. WINDOWS XP 显示结果: D:\source>test Read Data:13540757560943242
Linux发送端显示结果: [hq@h21 test]$ ./rea 1281942154 1058746368 1058746368 1058746368
由于printf显示长度问题所以导致显示结果与实际结果不一样.在GDB里面调试查看出结果与预期输入结果一样. file.txt文件采用flashget下载到本地.使用md5sum检验文件传输过程没有出错.
|