Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

String To A Byte Array
By David Kemp

preamble

this simple function converts a string to a byte[] that is in compliant with the visual c++ 6.0 BSTR/WCHAR.

why might you want to use it?

well for a start, for data compatability with those all programs you laboured over.

Another reason I use it is for eventlogging.

The EventLog class has an overloaded member function (WriteEntry) that allows you to end a byte array as the data for an event:public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData);

The value you pass as rawData appears in the Data pane when you view the Event\;s properties in the system\;s Event Viewer, thus:

figure 1 the data pane in the event properties

As you can see, the data pane provide an invaluable way of providing extra debugging information.

function declaration

protected internal void StringToByteArray(string theString, ref byte[] data, int offset) 
{
    int realI = 0;
    for(int i = 0; i < theString.Length; ++i)
    {
        realI = (i*2) + offset;
        data[realI] = (byte)(theString[i] & 0xFF);
        data[realI + 1] = (byte)((theString[i] & 0xFF00) >> 16);

    }
}

notes

the first thing to note is that no error checking occurs and that it\;s therefore very probable that exceptions will be thrown if the byte[] isn\;t big enough.

the offset parameter allows you to specify an offset, in bytes, from the start of the data array, to start copying into. It is important to realise that this is in bytes, as each element of a string is two bytes long.

example

string firstName = "Bill";
string surname = "Gates";

//for compatability with vc++6, remember to pad each string with two zero bytes at the end.
//also, as we\;re putting a space in the middle of the string, we need to add an extra two bytes.

byte[] bData = new byte[(firstName.Length + surname.Length) * 2 + 4] ;

StringToByteArray(firstName + " ", ref bData, 0); //copies firstName into the bData array

StringToByteArray(surname, ref bData,  (firstName.Length * 2) + 2);
//remember, each element in a string is two bytes long, and the space we added abve will count as an extra 2 bytes.