convert byte[] to string and way around

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

how to typecast or convert a byte[] to a string and the way arount ?
I have string from a textbox and wants to transmit it trough a socket. witch
accepts a byte[]. Now I make a copy from the string first, but I'm sure there
is some other way. For receiving I have to display the received string into
a textbox. same question ?
 
how to typecast or convert a byte[] to a string and the way arount ?
I have string from a textbox and wants to transmit it trough a socket. witch
accepts a byte[]. Now I make a copy from the string first, but I'm sure there
is some other way. For receiving I have to display the received string into
a textbox. same question ?


Check out this class: "BitConverter"
 
Hi,

string s = System.Text.Encoding.UTF8.GetString(bytes);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
 
Hi,

thank it is workinbut followig proble ifr receiving data:

private void DoDataAvailable(byte[] buffer, int offset, int count)

how to convert this to string ? offset is offset begin of string, and count
is amountof data.
 
Wilfried Mestdagh said:
thank it is workinbut followig proble ifr receiving data:

private void DoDataAvailable(byte[] buffer, int offset, int count)

how to convert this to string ? offset is offset begin of string, and count
is amountof data.

Denny already showed you the code - use Encoding.GetString.
 
Hi Jon,

Sorr I was not clear in this question. I have a pointer to a buffer with
offset in ti where data start, and count of data. To convert to string now I
need to make a double copy whitch should not be. I show because it will
explain better:

private void DoDataAvailable(byte[] buffer, int offset, int count)
{
count -= 2; // remove \r\n
byte[] tmp = new byte[count];
while (--count >= 0)
tmp[count] = buffer[offset + count];
string rx = Encoding.UTF8.GetString(tmp);

I wanted to avoid the extra copy of the data in tmp here.

thx, Wilfried
 
Wilfried Mestdagh said:
Sorr I was not clear in this question. I have a pointer to a buffer with
offset in ti where data start, and count of data. To convert to string now I
need to make a double copy whitch should not be. I show because it will
explain better:

private void DoDataAvailable(byte[] buffer, int offset, int count)
{
count -= 2; // remove \r\n
byte[] tmp = new byte[count];
while (--count >= 0)
tmp[count] = buffer[offset + count];
string rx = Encoding.UTF8.GetString(tmp);

I wanted to avoid the extra copy of the data in tmp here.

Use the overload of Encoding.GetString which takes a start index and a
count.
 
Back
Top