How can i convert for example byte[] b = new byte[1]; b[1]=255 to string ?
I need a string variable with the value "255" string text= "255";and then store it in a text file?
-
Admits to confusion.....Tony Hopkinson– Tony Hopkinson2012-11-21 22:21:14 +00:00Commented Nov 21, 2012 at 22:21
-
What's stored in that array? characters?Rashack– Rashack2012-11-21 22:21:36 +00:00Commented Nov 21, 2012 at 22:21
Add a comment
|
2 Answers
Starting from bytes:
byte[] b = new byte[255];
string s = Encoding.UTF8.GetString(b);
File.WriteAllText("myFile.txt", s);
and if you start from string:
string x = "255";
byte[] y = Encoding.UTF8.GetBytes(x);
File.WriteAllBytes("myFile2.txt", y);
6 Comments
Jesse Webb
That will not produce the string
"255", it will return the UTF8 character which the byte value 255 represents.Gregor Primar
As @Dave wrote question is not clear. So my point was to show OP how to convert between bytes and string and write result to file. I am sure this is all he needs in this case.
redfrogsbinary
no i am sorry i didn't mean that. I need a byte b=255; to produce a string text="255";
Gregor Primar
Well this is not a problem if you want just that: byte bValue = 255; string sValue = bValue.ToString();
redfrogsbinary
And what if bValue is an array? byte bValue[] I guess bValue[k].ToString();
|
No need to convert to string. You can just use File.WriteAllBytes
File.WriteAllBytes(@"c:\folder\file.txt", byteArray);
1 Comment
redfrogsbinary
But what if I wanted a string before writing the txt file?