I have this code:
Int32 i1 = 14000000;
byte[] b = BitConverter.GetBytes(i1);
string s = System.Text.Encoding.UTF8.GetString(b);
byte[] b2 = System.Text.Encoding.UTF8.GetBytes(s);
Int32 i2 = BitConverter.ToInt32(b2,0);;
i2 is equal to -272777233. Why isn't it the input value? (14000000) ?
EDIT: what I am trying to do is append it to another string which I'm then writing to file using WriteAllText
You shouldn't use Encoding.GetString
to convert arbitrary binary data into a string. That method is only intended for text that has been encoded to binary data using a specific encoding.
Instead, you want to use a text representation which is capable of representing arbitrary binary data reversibly. The two most common ways of doing that are base64 and hex. Base64 is the simplest in .NET:
string base64 = Convert.ToBase64String(originalBytes);
...
byte[] recoveredBytes = Convert.FromBase64String(base64);
A few caveats to this:
See more on this question at Stackoverflow