How to convert ascii char to byte in c#

随声附和 提交于 2020-04-12 07:41:27

问题


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.


回答1:


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");



回答2:


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



来源:https://stackoverflow.com/questions/45637214/how-to-convert-ascii-char-to-byte-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!