user34537
user34537

Reputation:

How do i compare a byte[] to string?

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

Upvotes: 2

Views: 8847

Answers (2)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

use

byte [] fromString = Encoding.Default.GetBytes("helloworld");

Upvotes: 1

Jeff Meatball Yang
Jeff Meatball Yang

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

Related Questions