Mike
Mike

Reputation: 2386

Creating a string from a byte[] variable (C#)

I am attempting to create a variable or string from "Convert.ToChar(b[i])" within the following context:

    byte[] b = new byte[100];
    int k = s.Receive(b);
    Console.WriteLine("Recieved...");
    for (int i = 0; i < k; i++)
        Console.Write(Convert.ToChar(b[i]));

E.g.:

var str = Convert.ToChar(b[i]);

But the above does not work, as "i" is not defined within the current context

Upvotes: 0

Views: 837

Answers (3)

TehBoyan
TehBoyan

Reputation: 6890

That's because i exists only within the for loop. Try adding all the values into an array and then access a specific item from it.

In your case, since you want to create a string in your code you could use StringBuilder to create the string. For example:

StringBuilder a = new StringBuilder();
a.Append(Convert.ToChar(b[i]);
string str = a.ToString();

or in your example it would be:

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
StringBuilder a = new StringBuilder();

for (int i = 0; i < k; i++)
{
    a.Append(Convert.ToChar(b[i]);
}
string str = a.ToString();

Upvotes: 1

ZombieSheep
ZombieSheep

Reputation: 29953

Is it just a case of the for loop not being given adequate scope? Try the following...

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
{
    Console.Write(Convert.ToChar(b[i]));
    var myVariable = Convert.ToChar(b[i]);
}

Note that if you didn't include the curly braces, the for loop would only have scope of the first line beneath it, and so the var = Convert.ToChar(b[i]); line would not be able to access the i variable in the loop scope.

That's why I always make sure I put the curly braces in the code for a loop, even if it is for a single line within the loop - it is easy to track the scope of the loop that way.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500385

It's fairly unclear what you mean, but it sounds like you might want:

byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Received...");
string text = Encoding.ASCII.GetString(b, 0, k);

Note that ASCII isn't the only possible encoding here - the correct one to use will depend on what the protocol you're using dictates.

Upvotes: 1

Related Questions