c#中将整数转化为字符串_在C#中将字符串转换为字节数组

c#中将整数转化为字符串

Prerequisite: How to declare and use byte[] in C#?

先决条件: 如何在C#中声明和使用byte []?

C#中的字符串到字节数组的转换 (String to Byte Array Conversion in C#)

In C#, it is possible that a string can be converted to a byte array by using Encoding.ASCII.GetBytes() method, it accepts a string as a parameter and returns a byte array.

在C#中, 可以使用Encoding.ASCII.GetBytes()方法将字符串转换为字节数组 ,它接受字符串作为参数并返回字节数组。

Note: In C#, the string contains two bytes per character; the method converts it into 1 byte. Still, sometimes it is possible to lose the data.

注意:在C#中,字符串每个字符包含两个字节;每个字符包含两个字节。 该方法将其转换为1个字节。 但是,有时仍可能会丢失数据。

Syntax:

句法:

Method Encoding.ASCII.GetBytes() contains various overloaded methods, here we are using the following method type...

方法Encoding.ASCII.GetBytes()包含各种重载方法,这里我们使用以下方法类型...

    byte[] Encoding.ASCII.GetBytes(String_Object);

Example:

例:

This example contains a constant string and converting it to byte[]

本示例包含一个常量字符串,并将其转换为byte []

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World! I am [email protected]";
            
            //reading all characters as byte and storing them to byte[]
            byte[] barr = Encoding.ASCII.GetBytes(str);

            //printing characters with byte values
            for(int loop =0; loop<barr.Length-1; loop++)
            {
                Console.WriteLine("Byte of char \'" + str[loop] + "\' : " + barr[loop]);
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

输出量

Byte of char 'H' : 72
Byte of char 'e' : 101
Byte of char 'l' : 108
Byte of char 'l' : 108
Byte of char 'o' : 111
Byte of char ' ' : 32
Byte of char 'W' : 87
Byte of char 'o' : 111
Byte of char 'r' : 114
Byte of char 'l' : 108
Byte of char 'd' : 100
Byte of char '!' : 33
Byte of char ' ' : 32
Byte of char 'I' : 73
Byte of char ' ' : 32
Byte of char 'a' : 97
Byte of char 'm' : 109
Byte of char ' ' : 32
Byte of char 'I' : 73
Byte of char 'n' : 110
Byte of char 'c' : 99
Byte of char 'l' : 108
Byte of char 'u' : 117
Byte of char 'd' : 100
Byte of char 'e' : 101
Byte of char 'H' : 72
Byte of char 'e' : 101
Byte of char 'l' : 108
Byte of char 'p' : 112
Byte of char '@' : 64
Byte of char '1' : 49
Byte of char '2' : 50
Byte of char '3' : 51


翻译自: https://www.includehelp.com/dot-net/convert-string-to-byte-array-in-c-sharp.aspx

c#中将整数转化为字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值