Reputation: 709
I am converting two properties string TokenValue
and TokenType
which is enum TokenType : byte
I am able to convert to a byte array using the below method and separating the two properties with a %.
public byte[] ToByteArray()
{
List<Byte> bytes = new List<byte>();
bytes.AddRange(Encoding.ASCII.GetBytes(TokenValue));
bytes.AddRange(Encoding.ASCII.GetBytes("%"));
bytes.Add((byte)this.TokenType);
return bytes.ToArray();
}
My problem is trying to convert back using:
public void FromByteArray(byte[] value)
{
Regex reg = new Regex("%");
string str = Encoding.UTF8.GetString(value);
string[] fields = reg.Split(str);
if (fields.Count() > 1)
{
TokenValue = fields[0];
TokenType = (TokenType)Encoding.ASCII.GetBytes(fields[1]); //Something along these lines to convert back to the TokenType
}
else if (fields.Count() == 1)
{
TokenValue = fields[0];
}
}
Not sure how to convert the bytes back to the enum TokenType
Thanks in advance.
Upvotes: 1
Views: 3377
Reputation: 13017
In ToByteArray()
you convert everything to bytes and then concatenate the byte values. Therefore, in FromByteArray()
, you need to split the byte array before you decode it into strings etc:
public void FromByteArray(byte[] value)
{
var delimiter = (byte)'%';
var stringBytes = value.TakeWhile(b => b != delimiter).ToArray();
var enumByte = 0;
if (stringBytes.Length < value.Length)
{
enumByte = value.Last();
}
TokenValue = Encoding.ASCII.GetString(stringBytes);
TokenType = (TokenType)enumByte;
}
Upvotes: 2