Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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])];
Posted
Updated 20-Dec-18 20:27pm

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);
 
Share this answer
 
Comments
Member 12440766 21-Dec-18 8:49am    
Thank you .... very very thanks
OriginalGriff 21-Dec-18 8:56am    
You're welcome!
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);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900