Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how can i build byte array with int values?

Status
Not open for further replies.

ccpro

Programmer
Apr 16, 2003
2
0
0
MX
4ex in C it would be like
char *str = sprintf("%c_some_string_%c", 0x2, 0x3);

how can i do the same in C# for sending byte array through socket?

tnx a lot
 
Sockets in .NET uses the NetworkStream class. This class has methods for reading and writing bytes, and byte arrays.
Code:
TcpClient client = new TcpClient("somehost.com", portNum);
NetworkStream ns = client.GetStream();
// Write a single byte
ns.WriteByte(0x20);

// Write an ASCII string
byte[] MyBytes = Encoding.ASCII.GetBytes("blahblahblah");
ns.Write(MyBytes, 0, MyBytes.Length);

// Write a Unicode UTF-8 string
MyBytes = Encoding.UTF8.GetBytes("moreblahblahblah");
ns.Write(MyBytes, 0, MyBytes.Length);

// Read a byte
int NumBytesRead = ns.ReadByte();
If (NumBytesRead == -1) {
   return;  // at end of stream
}

// Read an ASCII string
MyBytes = new Byte[8192];  // create buffer
NumBytesRead = ns.Read(MyBytes, 0, MyBytes.Length);
If (NumBytesRead == -1) {
   return;  // at end of stream
}
Console.WriteLine(Encoding.ASCII.GetString(MyBytes, 0, MyBytes.Length);

// Read a Unicode UTF8 string
MyBytes = new Byte[8192];  // create buffer
NumBytesRead = ns.Read(MyBytes, 0, MyBytes.Length);
If (NumBytesRead == -1) {
   return;  // at end of stream
}
Console.WriteLine(Encoding.UTF8.GetString(MyBytes, 0, MyBytes.Length);

client.Close();
 
the question wasn't about TcpClient,
the q is:
how to build byte array with int values?

tnx a lot
 
Not really sure if you are trying to build the byte array from int values or from a string, your original post looks like you are trying to do it from a string.

If you want to do it from int values then,
byte[] buffer = {0x1, 0x2, 0x3};

If you want to build a byte array from a string,
using System.Text;
byte[] buffer = Encoding.ASCII.GetBytes("Hello, World");

From char values,
using System.Text;
char[] charArray = {'h', 'e', 'l'};
byte[] buffer = Encoding.ASCII.GetBytes(charArray);
string myStr = Encoding.ASCII.GetString(buffer);

Aaron
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top