Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have byte array .i want to convert into string but including 0 value please help me?
Posted
Updated 20-Feb-15 20:46pm
v4
Comments
Thomas Daniels 21-Feb-15 2:30am    
Do you want a comma-separated list of the byte array with the 0, or do you want to convert it to a string by changing each byte into the ASCII char it represents?
Member 9027346 21-Feb-15 2:47am    
i want to convert it to a string by changing each byte into the ASCII char
Sergey Alexandrovich Kryukov 21-Feb-15 2:33am    
Why doing such things? What have you tried so far?
—SA
OriginalGriff 21-Feb-15 2:39am    
It depends what you actually want in the string:
5 characters, one for each byte value,
or the string "21,31,0,0,95"
The second is trivial, the first is dangerous as you may not be able to get your byte values back correctly for all byte values.

1 solution

"i want to convert it to a string by changing each byte into the ASCII char"

ASCII is easy:
C#
byte[] bytes = ...
string s = System.Text.Encoding.ASCII.GetString(bytes);



"but this method not joining zeros."

Um...are you sure?
C#
byte[] bytes = new byte[]{ 21, 31, 0, 0, 95 };
string s = System.Text.Encoding.ASCII.GetString(bytes);
foreach (char c in s)
    {
    Console.WriteLine((byte)c);
    }
Generates:
21
31
0
0
95
 
Share this answer
 
v2
Comments
Member 9027346 21-Feb-15 3:20am    
but this method not joining zeros.
OriginalGriff 21-Feb-15 3:30am    
Um...yes it does...see the modified answer...
Kuthuparakkal 22-Feb-15 20:39pm    
Great answer! my 5+

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