简体   繁体   English

TCP套接字C上的负数

[英]Negative Numbers over TCP socket C

Whenever I try to send a negative number over a TCP socket, when I print what was received,it reads "4.29497e+09". 每当我尝试通过TCP套接字发送负数时,当我打印收到的内容时,它将显示为“ 4.29497e + 09”。 All I'm doing is this: 我正在做的是这样的:

int i = -8;
int temp = htonl(i);
write(sock,&temp,4);

On the Server: 在服务器上:

int temp;
read(sock, &temp,4);
int read = ntohl(temp);
cout << read << endl;

If anyone could help, it would be much appreciated. 如果有人可以提供帮助,将不胜感激。

The htonl / ntohl functions are specifically for unsigned 32-bit integers. htonl / ntohl函数专门用于无符号的32位整数。

The htonl() function converts the unsigned integer hostlong from host byte order to network byte order. htonl()函数将无符号整数hostlong从主机字节顺序转换为网络字节顺序。

When transferring data over a socket, you don't need to convert it to network endianess. 通过套接字传输数据时,无需将其转换为网络耐久度。 This function is used to translate addresses, not actual data. 此功能用于转换地址,而不是实际数据。 These functions work with unsigned integers, so they don't match your argument (signed integer) 这些函数使用无符号整数,因此它们与您的参数(有符号整数)不匹配

You need to omit them. 您需要忽略它们。

If the second machine uses different endianess, which is kind of rare (both 8086 and ARM architectures work with little endian), you need to swap the bytes when reading ints and shorts. 如果第二台计算机使用不同的字节序(这很罕见)(8086和ARM架构都使用低字节序),则在读取int和shorts时需要交换字节。 This is usually done on the receiving socket. 这通常在接收套接字上完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM