Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ascii char to byte in c#

Tags:

c#

ascii

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.

like image 662
usmauriga Avatar asked Sep 18 '25 09:09

usmauriga


1 Answers

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");
like image 68
Johan Donne Avatar answered Sep 21 '25 01:09

Johan Donne