如何在C#中将ASCII字符转换为字节 [英] How to convert ascii char to byte in c#

查看:498
本文介绍了如何在C#中将ASCII字符转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我从ASCII转换为字节有问题.我有代码:

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

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

但是我不想从UTF-16转换为字节.在我的问题中,我想发送带ASCII码的字节.

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.

推荐答案

只需告诉编译器将char转换为字节:

just tell the compiler to convert the char to byte:

 byte b = (byte)'M';

或(请参阅上面的Adwaenyth的评论)

or (see comment of Adwaenyth above)

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

b的值为77(M为ASCII).

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

或输入字符串:

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

这篇关于如何在C#中将ASCII字符转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆