views:

1649

answers:

3

I have structure as follows:

struct data {int no; string name; int id};

I am converting this structure into bytearray. I need to convert this back into structure format. For that I need to convert first members into integer and string. How to convert bytearray into structure ?

+1  A: 

Well the answer really depends on how are you converting the structure into byte array. In theory, you will need to perform the same steps in reverse sequence!

For example if you serialize the structure such that:

  • first 4 bytes = no
  • second 4 bytes = id
  • rest bytes = byte stream of characters in name

then to convert the byte array back to structure, you just need to define a variable of that structure type and assign the members with values converted from byte array!

Hemant
+1  A: 

Check out the BitConverter class. Here's an example of how to convert byte array to int.

For string conversion BitConverter is not really useful (as Marc mentiones in his comment), even though it has the ToChar() method. You can use ASCIIEncoding, UTF8Encoding or any of the other XxxEncoding classes in the System.Text namespace instead.

Note, this is .Net specific.

Franci Penov
BitConverter won't help you with strings; and you need to be very careful about endianness (since BitConverter uses the CPUs endianness; not a fixed endianness such as network byte order).
Marc Gravell
Technically, BitConverter has the ToChar() which allows conversion to string. Not the best approach though, I agree.
Franci Penov
BitConverter for the Ints, and then Encoding.GetString() for the strings. The Encoding.GetString() may need management of the nul terminator.
Cheeso
+1  A: 

Note that many platforms include tools for this purpose; while you can write custom [de]serialization code, it can get tedious very quickly.

For example, google's protocol buffers is a language-agnostic* mechanism for describing a wire format. You can technically get better (smaller) serialization if you do everything by hand, but it will be a lot more work...

*= c++, java, etc in the google repo - plus lots more by the community

Marc Gravell