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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert a String to a Byte Array

Status
Not open for further replies.

ShankarJ

Programmer
Aug 9, 2003
856
Hi!

I am quite new to C# and am writing a COM wrapper for a .NET Control. One of the functions requires a Byte array as input and I am having problems passing a SafeArray from the calling application. The String object has a ToCharArray() method but none to convert to Byte array. Do I have to go through all the string characters and assign a VAL(SubStringChar) to the Byte array?

Regards
 
if it works... yes

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Hi Jason,

That means there is no other easier or proper way.

Regards
 
Hi!

Should have googled before asking here. Anyway, the solution is ::

Code:
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}

Code:
// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);

Regards
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top