在字符串和字节之间转换 [英] Converting between string and byte

查看:97
本文介绍了在字符串和字节之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨亲爱的

我希望你身体健康。

拜托,帮助我

如果我有一个字符串,我想要转换为byte的数组但是任何元素如果它等于字符串中的一个char

又怎么能回去



例如

第一个函数:

输入:字符串值=78a52f693d57e8cb;

输出字节[] R = {0x7; 0x8; 0xa; 0x5; 0x2; 0xf; 0x6; 0x9; 0x3; 0xd; 0x5; 0x7; 0xe; 0x8; 0xc; 0xb};





第二功能:

输入字节[] R = {0x7; 0x8; 0xa; 0x5; 0x2; 0xf; 0x6; 0x9; 0x3; 0xd; 0x5; 0x7; 0xe; 0x8; 0xc; 0xb};

输出:字符串值=78a52f693d57e8cb;



认为所有



我尝试了什么:


第一个功能


Hi dear
I hope you are healthy and well.
please, help me
If I have a string and I want to convert to array of byte but any elements if its is equal one char in string
and how can go back

for example
first function:
input: string value= "78a52f693d57e8cb";
output byte[] R={0x7;0x8;0xa;0x5;0x2;0xf;0x6;0x9;0x3;0xd;0x5;0x7;0xe;0x8;0xc;0xb};


second function:
input byte[] R={0x7;0x8;0xa;0x5;0x2;0xf;0x6;0x9;0x3;0xd;0x5;0x7;0xe;0x8;0xc;0xb};
output: string value= "78a52f693d57e8cb";

thinks for all

What I have tried:

for first function

string Stemp = "0123456789ABCDEF";
           byte[] Btemp = { 0x0, 0x1 , 0x2 , 0x3 , 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
           byte[] R = new byte[value.Length];
           foreach (char c in value)
           { R[z] = Btemp[Stemp.IndexOf(c)]; z = z + 1; }




第二个功能






for second function

char[] ty = new char[16];
 for (int i = 0; i < 16; i++)
                ty[i] = Stemp[Btemp.IndexOf(R[i])];

推荐答案

这是一个非常不寻常的要求,但它非常简单:

That's a very unusual requirement, but it's pretty trivial:
string value = "78a52f693d57e8cb";
byte[] R = new byte[value.Length];
int z = 0;
foreach (char c in value)
    {
    if (c >= '0' && c <= '9') R[z++] = (byte)(c - '0');
    else if (c >= 'A' && c <= 'F') R[z++] = (byte)(c - 'A' + 10);
    else if (c >= 'a' && c <= 'f') R[z++] = (byte)(c - 'a' + 10);
    else throw new ArgumentException("Bad hex digit: " + c);
    }
char[] ty = new char[R.Length];
for (int i = 0; i < R.Length; i++)
    {
    byte b = R[i];
    if (b >= 0 && b <= 9) ty[i] = (char)(b + '0');
    else if (b >= 10 && b <= 15) ty[i] = (char)(b - 10 + 'A');
    else throw new ArgumentException("Bad hex digit: " + b);
    }
string output = new string(ty);


字符串表示和数值不相同。



在你的字节中你使用过数值。



看看ASCII图表,ASCII字符会告诉你,0从48开始(0x30),a-97(0x61),A-65(0x41)



为了从0获得零值的ASCII值,你需要添加48(0x30)和0

从0获得0你需要减去48(0x30);



String representation and numeric value is not same.

In your byte you have used numeric value.

Take a look at ASCII chart, ASCII char will tell you, 0 starts at 48(0x30), a-97(0x61), A-65(0x41)

In order to get ASCII value of zero from 0, you need to add 48(0x30) with 0
To get 0 from zero you need to subtract 48(0x30);

// example
char [] c = { (char)48, (char)49, (char)50 };
            String s = new string(c);
            Console.WriteLine("First String : "+s);


这篇关于在字符串和字节之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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