C# 数据类型转化为byte数组
项目当中经常遇到将short 、string、int等类型的数据转换成字节数组,以便将数据以数据流的形式进行缓存、传递的情况(例如MemoryStream),现将常见的转换形式总结一下:
1.short数据与byte数组互转
public byte[] ShortToByte(short value)
{
return BitConverter.GetBytes(value);
}
public short ByteToShort(byte[] arr)
{
return BitConverter.ToInt16(arr,0);
}
2.string数据与byte数组互转
public byte[] StringToByte(string value)
{
return Encoding.UTF8.GetBytes(value);
//return Text.Encoding.Default.GetBytes (value);
}
public string ByteToString(byte[] arr)
{
return Encoding.UTF8.GetString(arr);
//return Text.Encoding.UTF8.GetString (arr, 0, arr.Length);
}
3.int数据与byte数组互转
public byte[] IntToByte(short value)
{
return BitConverter.GetBytes(value);
}
public int ByteToInt(byte[] arr)
{
return BitConverter.ToInt(arr,0);
}
其它数据类型类似,不一一列举!