Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Int to Byte and then back to Int does not return the same value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading