Home > Software engineering >  Int to Byte and then back to Int does not return the same value
Int to Byte and then back to Int does not return the same value

Time:07-01

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?

CodePudding user response:

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)
  • Related