int到字节然后返回int不会返回相同的值

发布于 2025-02-12 00:43:29 字数 701 浏览 0 评论 0原文

我必须通过网络发送整数值数组。它们只能以字节数组字节[]发送。

但是问题是,当另一个设备接收到的字节时 - 转换回int时不会给出相同的值?

下面的代码及其输出是我面临的问题

int x = GetUniqueID();
Debug.Log("Int value is: " + x.ToString());
byte b = (byte)x;
Debug.Log("Converted to byte is: " + b.ToString());
int y = (int)b;
Debug.Log("Converted back to int is: " + y.ToString());

private int GetUniqueID()
    {
        int x;
        x = Random.Range(0, 1000);

        return x;
    }

,这是上述代码的控制台输出(运行两次):

“在此处输入映像”

为什么在int转换为byte之后,为什么未返回原始值?

I have to send an array of integer value over the network. They can only be sent as a byte array byte[].

But the problem is that when that byte that is received by the other device - when converted back to int does not give the same value?

Below code and its output is the problem that I am facing

int x = GetUniqueID();
Debug.Log("Int value is: " + x.ToString());
byte b = (byte)x;
Debug.Log("Converted to byte is: " + b.ToString());
int y = (int)b;
Debug.Log("Converted back to int is: " + y.ToString());

private int GetUniqueID()
    {
        int x;
        x = Random.Range(0, 1000);

        return x;
    }

And here is the console output of the above code (run twice):

enter image description here

Why is the original value not returned after the int is converted to byte?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

无可置疑 2025-02-19 00:43:30

您将int(32位或4个字节)施放为一个单个字节 byte 。这会导致您的价值被截断,这就是为什么您看到它在示例中从344减少到88的原因。

而是尝试使用 bitconverrer class将int转换为byte []

byte[] b = BitConverter.GetBytes(x)

You are casting an int, which is 32 bits or 4 bytes, into a byte which is a single byte. This causes your value to be truncated, which is why you are seeing it reduce from 344 to 88 in your example.

Instead try using the BitConverter class to convert an int into a byte[]

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