在上位机开发过程中,会面对各种数据类型,而各种数据类型之间的转换是很多初学者非常头疼的。本章内容主要是介绍各种常用的数据类型及其之间的相互转换。
字节顺序简单来讲,就是指超过一个字节的数据类型在内存中的储存顺序,如果只有一个字节就不存在顺序这一说。字节顺序一般来说分为两类,一类叫大端字节顺序,一类叫小端字节顺序。字节顺序与硬件相关,也和协议相关,但无论如何,它都是确定值,是不会变化的,即要么是大端法,要么是小端法,不存在一会儿大端,一会儿小端。
降序(Big-endian):大端字节序存储时,由左到右,即高位字节储存在内存低位地址中,低位字节储存在内存高位地址中。
升序(Little-endian):小端字节序存储时,由右向左,即高位字节储存在内存高位地址中,低位字节储存在内存低位地址中。
严格来讲这不算是个数据类型,这个主要是用于编写通讯库。通讯中的报文一般都是字节数组,但字节数组使用起来没有List集合使用起来方便。
public class ByteArray
{
private List<byte> list = new List<byte>();
///
/// 属性,返回字节数组
///
public byte[] array
{
get { return list.ToArray(); }
}
///
/// 清空字节数组
///
public void Clear()
{
list = new List<byte>();
}
///
/// 添加一个字节
///
/// 字节
public void Add(byte item)
{
list.Add(item);
}
///
/// 添加一个字节数组
///
/// 字节数组
public void Add(byte[] items)
{
list.AddRange(items);
}
///
/// 添加一个ByteArray对象
///
/// ByteArray对象
public void Add(ByteArray byteArray)
{
list.AddRange(byteArray.array);
}
}
public static bool GetBitFromByte(byte b, int offset)
{
if (offset >= 0 && offset <= 7)
{
return (b & (int)Math.Pow(2, offset)) != 0;
}
else
{
throw new Exception("索引必须为0-7之间");
}
}
public static byte[] GetByteArray(byte[] source, int start, int length)
{
byte[] Res = new byte[length];
if (source != null && start >= 0 && length > 0 && source.Length >= (start + length))
{
Array.Copy(source, start, Res, 0, length);
return Res;
}
else
{
return null;
}
}
public static int GetIntFromByteArray(byte[] source, int start = 0)
{
byte[] b = ByteArrayLib.GetByteArray(source, start, 4);
return b==null?0: BitConverter.ToInt32(b, 0);
}
public static float GetFloatFromByteArray(byte[] source, int start = 0)
{
byte[] b = ByteArrayLib.GetByteArray(source, start, 4);
return b == null ? 0.0f : BitConverter.ToSingle(b, 0);
}