MxLDevs
MxLDevs

Reputation: 19546

C# safe way to convert between bytes and other types

What is the safest way to guarantee that the following operation will be performed correctly:

When I read in 4 bytes as a uint32, I will write it out to a text file. Later I will open this text file, read the number I wrote out previously, and then convert it back into the 4 bytes for use in other processing.

Upvotes: 0

Views: 183

Answers (2)

Kirk Woll
Kirk Woll

Reputation: 77586

Since you are storing this as a string, there isn't a whole lot to this. Obviously there is no issue converting the number into a string using .ToString(). So the only question I assume is how to go back in a reliable fashion. The solution is to use uint.Parse. i.e.:

var s = "12343632423432";
uint i = uint.Parse(s);

(PS: BitConverter is not helpful for conversion from strings)

Upvotes: 1

Jf Beaulac
Jf Beaulac

Reputation: 5246

There is the BitConverter class to help you convert between primitive types and bytes.

Upvotes: 3

Related Questions