1

I've got a bunch of data that I need serialized into a string to be stored in a KVP. I've got tons of ints, bools, and floats. I take each one, BitConverter it into a byte[] that I am Buffer.BlockCopying into a single large byte[].

I need to save this large array of bytes as a string in a KeyValuePair<string, string>. I tried using Encoding.ASCII.GetString() with the big byte[] I created, and then I tried to reload my level with the string code achieved using Encoding.ASCII.GetBytes().

m_LevelCode = Encoding.ASCII.GetString( bytes );

The array of bytes has tons of 0's, so I'm guessing that's why my m_LevelCode string is an empty string.

Is there a better approach to what I'm trying to do? I have about 650 bytes worth of integers, booleans, and floats. I need them to be saved into a string. One step further, I'd like to comma separate 5 of these into a single KVP to conserve on individual keys since every area has 5 levels.

3
  • 2
    Note that ASCII doesn't allow for arbitrary octets to be encoded within it (it's a 7-bit charset). You probably want to use base64 or similar at some point if you want this to be a proper ASCII string. I'm no C# expert (never used it, in fact), but that may be the reason for some/all of the zeroes--they are just bytes that can't encode directly in ASCII. Commented Sep 12, 2016 at 22:59
  • Thanks BJ, I'll need to do a couple more tests but at first glance that looks like that might be the problem! Commented Sep 12, 2016 at 23:29
  • If you decode 0 as ASCII, you'll get U+0000 in your string. The length of m_LevelCode should be the same as bytes because UTF-16 encodes any character that ASCII can provide as one code unit (char). Commented Sep 13, 2016 at 2:58

1 Answer 1

2

There are many ways to convert the bytes to a string

string base64 = Convert.ToBase64String(bytes);

string hex = BitConverter.ToString(bytes);

var jss = new JavaScriptSerializer();
string json = jss.Serialize(bytes);

where bytes is byte array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.