string to byte array c# code example
Example 1: c# string to byte array
string author = "Mahesh Chand";
byte[] bytes = Encoding.ASCII.GetBytes(author);
string str = Encoding.ASCII.GetString(bytes);
Example 2: string from byte array c#
var str = System.Text.Encoding.Default.GetString(result);
Example 3: c# string to byte array
string someText = "some data as text.";
byte[] bytes = Encoding.ASCII.GetBytes(author);
string str = Encoding.ASCII.GetString(bytes);
Console.WriteLine(str);
Example 4: c# class to byte array
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
private Object ByteArrayToObject(byte[] arrBytes)
{
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object) binForm.Deserialize(memStream);
return obj;
}
Example 5: c# string to byte[]
using System.Text;
public static byte[] encode(string stringToEncode)
{
UTF8Encoding utf8 = new UtF8Encoding();
byte[] bytename = new byte[1024];
bytename = utf8.GetBytes(stringToEncode);
return bytename;
}
Example 6: c# number to byte array
public byte[] ConvertNumToByte(int Number)
{
byte[] ByteArray = new byte[32];
string BinString = Convert.ToString(Number, 2);
char[] BinCharArray = BinString.ToCharArray();
try
{
System.Array.Reverse(BinCharArray);
if (BinCharArray != null && BinCharArray.Length > 0)
{
for (int index = 0; index < BinCharArray.Length; ++index)
{
ByteArray[index] = Convert.ToByte(Convert.ToString(BinCharArray[index]));
}
}
}
catch
{
}
return ByteArray;
}