c# - Byte array to struct -


i'm having trouble converting string parts of byte array.

my struct looks this:

[structlayout(layoutkind.sequential, pack = 1)] struct message {     public int id;      [marshalas(unmanagedtype.byvaltstr, sizeconst = 10)]     public string text; } 

creation of test byte array:

private static byte[] createmessagebytearray() {     int id = 69;     byte[] intbytes = bitconverter.getbytes(id);      string text = "test";     byte[] stringbytes = getbytes(text);      ienumerable<byte> rv = intbytes.concat(stringbytes);      return rv.toarray(); } 

method convert bytearray struct:

static t bytearraytostructure<t>(byte[] bytes) t : struct {     var handle = gchandle.alloc(bytes, gchandletype.pinned);     var result = (t)marshal.ptrtostructure(handle.addrofpinnedobject(), typeof(t));     handle.free();     return result; } 

when call bytearraytostructure result createmessagebytearray() struct id=60 , text="t".

why don't whole string e.g "test" ?

edit: code forgot pase:

    static byte[] getbytes(string str)     {         byte[] bytes = new byte[str.length * sizeof(char)];         system.buffer.blockcopy(str.tochararray(), 0, bytes, 0, bytes.length);         return bytes;     } 

the problem @ line:

byte[] stringbytes = getbytes(text); 

how converting string byte array? using unicode encoding, store each character 2 bytes, , because string in ascii set, every other byte zero:

byte[] stringbytes = new unicodeencoding().getbytes(text); // give { 't', '\0', 'e', '\0', 's', '\0', 't', '\0' } 

these zeroes mislead marshalling mechanism assuming terminal characters , string ends after 't'.

instead, can use ascii encoding (which stores 1 byte per character):

byte[] stringbytes = new asciiencoding().getbytes(text); // give { 't', 'e', 's', 't' } // lose non-ascii character information 

or can use utf8 encoding (which variable length):

byte[] stringbytes = new utf8encoding().getbytes(text); // give { 't', 'e', 's', 't' }     // , retain non-ascii character information, it's // trickier rebuild string correctly in case of non-ascii // information present 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -