Click here to Skip to main content
15,893,368 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have a string like this
\x00\x00\x00\x00\x00\x00\x00\x00
and I want to change it in a char array, like this : 00 00 00 00 00 00 00 00;

How can I made it like that?

Thanks.

What I have tried:

I have already tried the split function but it didn't worked.
Maybe I didn't use it right.
Posted
Updated 11-Sep-17 21:43pm

Do you mean
C#
string s = @"\x00\x00\x00\x00\x00\x00\x00\x00";
string[] a = s.Split(new string []{@"\x"},StringSplitOptions.RemoveEmptyEntries);
char[] ca = new char[a.Length];
for (int k = 0; k < a.Length; ++k)
  ca[k] = System.Convert.ToChar(System.Convert.ToUInt32(a[k], 16));
?
 
Share this answer
 
That is a C source file string specifying hex codes for the characters.

If you really have such a string (that is character codes 0x5C 0x78 0x30 0x30) you can remove the "\x" from the string and convert the resulting string to a byte array. That can be than converted to a char array (but it might not be necessary depending on what you want to do with it).

To remove the "\x" you can use
C#
String.Replace(@"\x", "");
or
C#
String.Replace("\\x", "");

There are many examples to convert the resulting string to a byte array. Just search the net for something like "c# hex string to byte array":
c# - How can I convert a hex string to a byte array? - Stack Overflow[^]
 
Share this answer
 
That's going to depend on what your string is exactly - and there are two possibilities
Here's one:
C#
string inp = @"\x00\x00\x00\x00\x00\x00\x00\x00";

And here's the other:
C#
string inp = "\x00\x00\x00\x00\x00\x00\x00\x00";

How you need to handle them is different.
The first is fairly trivial:
C#
string inp = @"\x00\x00\x00\x00\x00\x00\x00\x00";
string[] values = inp.Split(new string[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
char[] data = new char[values.Length];
int i = 0;
foreach (string s in values)
    {
    data[i++] = (char)Convert.ToByte(s, 16);
    }
The second is even more trivial: a string is a char array, effectively in that you can access individual characters via an index, but:
C#
string inp = "\x00\x00\x00\x00\x00\x00\x00\x00";
char[] data = inp.ToArray();
 
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