[英]C# Convert a string to ASCII bytes
I have a string: 我有一个字符串:
LogoDataStr = "ABC0000"
I want to convert to ASCII bytes and the result should be: 我想转换为ASCII字节,结果应为:
LogoDataBy[0] = 0x41;
LogoDataBy[1] = 0x42;
LogoDataBy[2] = 0x43;
LogoDataBy[3] = 0x30;
LogoDataBy[4] = 0x30;
LogoDataBy[5] = 0x30;
LogoDataBy[6] = 0x30;
I've tried using this way: 我尝试过使用这种方式:
byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes(LogoDataStr);
But the result I get is this: 但是我得到的结果是这样的:
LogoDataBy[0] = 0x41;
LogoDataBy[1] = 0x42;
LogoDataBy[2] = 0x43;
LogoDataBy[3] = 0x00;
LogoDataBy[4] = 0x00;
LogoDataBy[5] = 0x00;
LogoDataBy[6] = 0x00;
Is there any wrong with my coding? 我的编码有问题吗?
This code 这段代码
class Program
{
static void Main(string[] args)
{
byte[] LogoDataBy = ASCIIEncoding.ASCII.GetBytes("ABC000");
}
}
produces expected output 产生预期的产出
Double check your code and the value of the string before you read ASCII bytes. 在读取ASCII字节之前,请仔细检查您的代码和字符串的值。
Just throwing: 只是抛出:
Encoding.ASCII.GetBytes("ABC0000").Dump();
Into LinqPAD gives an output of (decimal): 到LinqPAD中,输出为(十进制):
Byte[] (7 items) 字节[](7个项目)
65 65岁
66 66
67 67
48 48
48 48
48 48
48 48
So I'm not sure how you're getting 0x00... 所以我不确定你怎么得到0x00 ...
class CustomAscii
{
private static Dictionary<char, byte> dictionary;
static CustomAscii()
{
byte numcounter = 0x30;
byte charcounter = 0x41;
byte ucharcounter = 0x61;
string numbers = "0123456789";
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string uchars = "abcdefghijklmnopqrstuvwxyz";
dictionary = new Dictionary<char, byte>();
foreach (char c in numbers)
{
dictionary.Add(c, numcounter++);
}
foreach (char c in chars)
{
dictionary.Add(c, charcounter++);
}
foreach (char c in uchars)
{
dictionary.Add(c, ucharcounter++);
}
}
public static byte[] getCustomBytes(string t)
{
int iter = 0;
byte[] b = new byte[t.Length];
foreach (char c in t)
{
b[iter] = dictionary[c];
//DEBUG: Console.WriteLine(b[iter++].ToString());
}
return b;
}
}
This is how i would do it. 这就是我会做的。 JUST IF Encoding.ASCII.GetBytes() would return wrong values. 仅在Encoding.ASCII.GetBytes()会返回错误的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.