Reputation:
I want to compare the first few bytes in byte[] with a string. How can i do this?
Upvotes: 2
Views: 8847
Reputation: 40497
use
byte [] fromString = Encoding.Default.GetBytes("helloworld");
Upvotes: 1
Reputation: 39017
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.
Upvotes: 10