将 64 位 int 值写入 NSOutputStream

发布于 2024-09-08 23:25:51 字数 379 浏览 6 评论 0原文

我在将位置坐标传送到网络上连接的一组电机时遇到问题。我可以很好地发送一个字符串,并从电机接收回文本,但我似乎无法向它发送一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫弦 2024-09-15 23:25:51

嗯,你的代码看起来有点有趣。无论如何,为了通过网络发送二进制整数,您必须知道字节序:接收器期望小字节序或大字节序整数。

这是两者的代码:

uint64_t myInt = 42;

uint64_t netInt = CFSwapInt64HostToLittle(myInt); // use this for little endian
uint64_t netInt = CFSwapInt64HostToBig(myInt);    // use this for big endian

[outputStream write:(uint8_t*)&netInt maxLength:sizeof(netInt)];

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:

uint64_t myInt = 42;

uint64_t netInt = CFSwapInt64HostToLittle(myInt); // use this for little endian
uint64_t netInt = CFSwapInt64HostToBig(myInt);    // use this for big endian

[outputStream write:(uint8_t*)&netInt maxLength:sizeof(netInt)];
回梦 2024-09-15 23:25:51

您可能会遇到字节顺序问题。 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文