int到字节然后返回int不会返回相同的值
我必须通过网络发送整数值数组。它们只能以字节数组字节[]
发送。
但是问题是,当另一个设备接收到的字节时 - 转换回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):
Why is the original value not returned after the int is converted to byte?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将
int
(32位或4个字节)施放为一个单个字节 byte 。这会导致您的价值被截断,这就是为什么您看到它在示例中从344减少到88的原因。而是尝试使用 bitconverrer class将
int
转换为byte []
You are casting an
int
, which is 32 bits or 4 bytes, into abyte
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 abyte[]