如何将int转换为字节数组然后返回? [英] How do I convert a int to an array of byte's and then back?

查看:59
本文介绍了如何将int转换为字节数组然后返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过NetworkStream发送一个整数.问题是我只能发送字节.这就是为什么我需要将整数分成四个字节并将其发送,然后在另一端将其转换回int.

I need to send an integer through a NetworkStream. The problem is that I only can send bytes. Thats why I need to split the integer in four byte's and send those and at the other end convert it back to a int.

现在我仅在C#中需要它.但是对于最终项目,我将需要将这四个字节转换为Lua中的int.

For now I need this only in C#. But for the final project I will need to convert the four bytes to an int in Lua.

在Lua怎么样?

推荐答案

尝试

BitConverter.GetBytes()

BitConverter.GetBytes()

http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx

请记住,返回数组中字节的顺序取决于系统的字节顺序.

Just keep in mind that the order of the bytes in returned array depends on the endianness of your system.

至于Lua部分,我不知道如何转换回来.您总是可以乘以16来获得按位移位4的相同功能.这不是很漂亮,我可以想象有一些实现它的库.同样,添加字节的顺序取决于字节序,因此您可能需要阅读

As for the Lua part, I don't know how to convert back. You could always multiply by 16 to get the same functionality of a bitwise shift by 4. It's not pretty and I would imagine there is some library or something that implements it. Again, the order to add the bytes in depends on the endianness, so you might want to read up on that

也许您可以转换回C#?

Maybe you can convert back in C#?

这篇关于如何将int转换为字节数组然后返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆