How do i compare a byte[] to string?

arrays, c#, string

Solution

You must know the encoding of the byte array to properly compare them.

For example, if you know your byte array is made of UTF-8 bytes, then you can create a string from the byte array:

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string s = enc.GetString(originalBytes);

Now you can compare string s to your other string.

Conversely, if you want to compare just the first few bytes, you can convert the string into a UTF8 byte array:

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] b = enc.GetBytes(originalString);

Now you can compare byte array b to your other byte array.

There are several other encoding objects for ASCII, Unicode, etc. See the MSDN page here.

Problem

I want to compare the first few bytes in byte[] with a string. How can i do this?

Original source