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 arrayby 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#中将整數轉化為字元串