将 64 位 int 值写入 NSOutputStream
我在将位置坐标传送到网络上连接的一组电机时遇到问题。我可以很好地发送一个字符串,并从电机接收回文本,但我似乎无法向它发送一个 int 值。
使用 NSlog 我已经确定我发送的实际值是正确的,但是我怀疑我通过输出流发送它的方法是错误的。有什么想法吗?
我发送 64 位 int 值的代码:
uint64_t rawInt = m1;
rawInt <<= 16;
rawInt |= m2;
NSData *buffer = [NSData dataWithBytes: &rawInt length:8];
[outputStream write: [buffer bytes] maxLength:[buffer length]];
I'm having trouble communicating position coordinates to a set of motors I have connected on the network. I can send a string just fine, and receive text back from the motor, but I can't seem to send it an int value.
Using NSlog I have determined that the actual value I'm sending is correct, however I suspect my method of sending it via the output stream is wrong. Any ideas?
My code for sending a 64bit int value:
uint64_t rawInt = m1;
rawInt <<= 16;
rawInt |= m2;
NSData *buffer = [NSData dataWithBytes: &rawInt length:8];
[outputStream write: [buffer bytes] maxLength:[buffer length]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,你的代码看起来有点有趣。无论如何,为了通过网络发送二进制整数,您必须知道字节序:接收器期望小字节序或大字节序整数。
这是两者的代码:
Well, your codes looks kind of funny. Anyway, for sending a binary integer over the network, you have to know the endianess: The receiver either expects little or big endian integers.
Here's the code for both:
您可能会遇到字节顺序问题。 Intel CPU 是little-endian,这意味着多字节值中的最低有效字节首先存储,最高有效字节最后存储。从内存中读取 8 字节数字并将其放在网络上而不执行任何操作将导致字节按该顺序输出。
大多数网络协议(包括所有互联网协议)都期望大端数据,因此最高有效字节首先出现在网络上,最低有效字节最后出现。您的网络协议是否期望如此?
You're probably seeing an endianness problem. Intel CPUs are little-endian, meaning that the least significant byte in a multi-byte value is stored first, the most significant byte last. Reading an 8-byte number from memory and putting it on the network without doing anything will cause the bytes to go out in that order.
Most network protocols (including all internet protocols) expect big-endian data, so the most significant byte appears on the network first and the least significant byte last. Does your network protocol expect that?