vote up 0 vote down star
1

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 ?

flag

75% accept rate
1  
What language / architecture? A c++ answer and a C#/.NET answer will look very different! – Marc Gravell Feb 26 '09 at 8:09

3 Answers

vote up 1 vote down check

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.

link|flag
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 Feb 26 '09 at 8:16
Technically, BitConverter has the ToChar() which allows conversion to string. Not the best approach though, I agree. – Franci Penov Feb 26 '09 at 8:25
BitConverter for the Ints, and then Encoding.GetString() for the strings. The Encoding.GetString() may need management of the nul terminator. – Cheeso Feb 26 '09 at 10:56
vote up 1 vote down

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!

link|flag
vote up 1 vote down

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

link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.