C4d
C4d

Reputation: 3272

Convert char[] to byte[] results in higher count

Im trying to cast a char-array into a byte-array.

char[] cc = new char[] { ((char)(byte)210) }; // Count = 1
byte[] b = System.Text.Encoding.UTF8.GetBytes(cc); // Count = 2

The conversion results in 2 entries for my byte-array {195, 146}.
I guess theres a problem with the encoding. Any help is appreciated.


After facing some problems I've written this 2 lines for the purpose of testing, so dont mind the style.

Thanks

Upvotes: 3

Views: 8013

Answers (2)

C4d
C4d

Reputation: 3272

As M.kazemAkhgary said in the comments above:

cc.Select(c=>(byte)c).ToArray();

The clue was to cast instead of using converting. Thanks for that!

Upvotes: 2

erg
erg

Reputation: 1652

UTF-8 can use more than just one byte to store a character. It uses only one byte for the ASCII characters within the range from 0-127, other characters need two or more bytes to be stored.

You are encoding the ASCII character 210 which is from the extended ASCII character (numeric value > 127), UTF-8 uses two bytes to store this character.

Upvotes: 3

Related Questions