usmauriga
usmauriga

Reputation: 93

How to convert ascii char to byte in c#

Hello I have a problem with conversion from ASCII to Byte. I have the code:

byte M = Convert.ToByte('M');

but this converts from UTF-16 to byte with I don't want. In my problem I would like to send bytes with ASCII codes.

Upvotes: 4

Views: 37589

Answers (2)

Johan Donne
Johan Donne

Reputation: 3285

just tell the compiler to convert the char to byte:

 byte b = (byte)'M';

or (see comment of Adwaenyth above)

byte b = Encoding.ASCII.GetBytes("M")[0];

b will have the value 77 (ASCII for M).

Or for a string:

byte[] b2 = Encoding.ASCII.GetBytes("text");

Upvotes: 17

Jimenemex
Jimenemex

Reputation: 3166

Why not use int a = 'm'; It converts the m into its ascii equivalent. You could then use it as you wish.

Upvotes: -1

Related Questions