Mega Code Archive

 
Categories / C# / Data Types
 

Conversion between C# string and packed string representation

using System; using System.IO; public class Utils {     public static byte[] PackString(String Source)     {         byte[] Value = StringToByteArray(Source);         Int32 ILength = Value.Length;         byte[] Result = new byte[4 + ILength];         Result[0] = (byte)((ILength >> 0) & 0xFF);         Result[1] = (byte)((ILength >> 8) & 0xFF);         Result[2] = (byte)((ILength >> 16) & 0xFF);         Result[3] = (byte)((ILength >> 24) & 0xFF);         for (Int32 i = 0; i < ILength; i++)             Result[4 + i] = Value[i];         return Result;     }     public static UInt32 UnpackUInt32(byte[] Value)     {         return             (UInt32)(Value[0] << 0) +             (UInt32)(Value[1] << 8) +             (UInt32)(Value[2] << 16) +             (UInt32)(Value[3] << 24);     }     public static byte[] StringToByteArray(String Source)     {         char[] CSource = Source.ToCharArray();         byte[] Result = new byte[CSource.Length];         for (Int32 i = 0; i < CSource.Length; i++)             Result[i] = Convert.ToByte(CSource[i]);         return Result;     } }