c# 不同数据类型转换

发布于:2025-02-11 ⋅ 阅读:(93) ⋅ 点赞:(0)
namespace System

public static class ConvertExtension
{
    public static byte[] ToBinaryByteArray(this byte[] bytes)
    {
        // 每个字节有 8 位,所以总位数为 bytes.Length * 8
        byte[] binaryArray = new byte[bytes.Length * 8];

        int index = 0;

        // 遍历每个字节
        foreach (byte b in bytes)
        {
            // 遍历字节的每一位
            for (int i = 0; i < 8; i++)
            {
                byte bit = (byte)(((b >> i) & 1));
                binaryArray[index++] = bit;
            }
        }

        return binaryArray;
    }

    public static int BinaryArrayToDecimal(this byte[] binaryArray)
    {
        int decimalValue = 0;
        int length = binaryArray.Length;

        for (int i = 0; i < length; i++)
        {
            if (binaryArray[i] == 1)
            {
                decimalValue += (int)Math.Pow(2, i);
            }
        }

        return decimalValue;
    }

    public static IEnumerable<T> ConvertRowMajorToColumnMajor<T>(this IEnumerable<T> rowMajor, int rows, int columns)
    {
        List<T> columnMajor = new List<T>();
        for (int col = 0; col < columns; col++)
        {
            for (int row = 0; row < rows; row++)
            {
				int index = row * columns + col;

                if (rowMajor.Count() <= index)
				{
					break;
				}

                columnMajor.Add(rowMajor.ElementAt(index));
            }
        }
        return columnMajor;
    }
    public static byte[] SwitchBytes(this byte[] data, int blockSize = 2)
	{
		if (data == null || data.Length < 2 || data.Length % blockSize != 0)
		{
			return null;
		}
		List<byte> bytes = new List<byte>();
		for (int i = 0; i < data.Length; i += blockSize)
		{
			byte[] temp = new byte[blockSize];
			Array.Copy(data, i, temp, 0, blockSize);
			bytes.AddRange(temp.Reverse());
		}
		return bytes.ToArray();
	}

	public static byte[] BytesReverse(this byte[] data)
	{
		return data?.Reverse().ToArray();
	}

	public static string BytesToStr(this byte[] data, Encoding encoding = null)
	{
		if (encoding == null)
		{
			return Encoding.Default.GetString(data);
		}
		return encoding.GetString(data);
	}

	public static byte HexToByte(this string str)
	{
		str = str.Replace(" ", "").Replace("\r", "").Replace("\n", "")
			.Replace("0x", "");
		if (string.IsNullOrEmpty(str))
		{
			return 0;
		}
		try
		{
			return Convert.ToByte(str, 16);
		}
		catch (Exception)
		{
			return 0;
		}
	}

	public static string ByteToHex(this byte data)
	{
		return Convert.ToString(data, 16).PadLeft(2, '0').ToUpper();
	}

	public static string ToHex(this byte data)
	{
		return Convert.ToString(data, 16).PadLeft(2, '0').ToUpper();
	}

	public static byte[] HexToBytes(this object value, bool isReverse = false)
	{
		return value.ToString().HexToBytes(isReverse);
	}

    public static bool[] HexToBoolBinary(byte[] hexBytes)
    {
        byte[] binaryBytes = new byte[hexBytes.Length * 8];
        bool[] res = new bool[hexBytes.Length * 8];

        for (int i = 0; i < hexBytes.Length; i++)
        {
            byte hexByte = hexBytes[i];

            for (int j = 0; j < 8; j++)
            {
                byte binaryBit = (byte)((hexByte >> (7 - j)) & 1);
                binaryBytes[i * 8 + j] = binaryBit;
                res[i * 8 + j] = binaryBit == 0 ? false : true;
            }
        }
        return res;
    }

    public static byte[] HexToBytes(this string str, bool isReverse = false)
	{
        if (string.IsNullOrEmpty(str))
        {
            return null;
        }

		if(str.Length==1)
		{
			str = str.PadLeft(2, '0');
		}

        str = str.Replace(" ", "").Replace("\r", "").Replace("\n", "");

        if (string.IsNullOrEmpty(str))
        {
            return null;
        }

        try
		{
			byte[] bytes = new byte[str.Length / 2];
			for (int i = 0; i < bytes.Length; i++)
			{
				bytes[i] = Convert.ToByte(str.Substring(2 * i, 2), 16);
			}
			if (isReverse)
			{
				bytes = bytes.Reverse().ToArray();
			}
			return bytes;
		}
		catch (Exception ex)
		{
			
			return null;
		}
	}

	public static byte[] StrToBytes(this string str, Encoding encoding = null)
	{
		str = str.Replace(" ", "").Replace("\r", "").Replace("\n", "");
		if (string.IsNullOrEmpty(str))
		{
			return null;
		}
		try
		{
			return (encoding == null) ? Encoding.UTF8.GetBytes(str) : encoding.GetBytes(str);
		}
		catch (Exception ex)
		{
			
			return null;
		}
	}

	public static string ToHex(this byte[] data, string pre, bool isWithSpace = false, bool isReverse = false)
	{
		if (data == null || data.Length < 1)
		{
			return null;
		}
		try
		{
			if (isReverse)
			{
				data = data.Reverse().ToArray();
			}
			StringBuilder sb = new StringBuilder(data.Length * 2);
			if (isWithSpace)
			{
				byte[] array = data;
				foreach (byte b2 in array)
				{
					sb.Append(Convert.ToString(b2, 16).PadLeft(2, '0').PadLeft(3, ' '));
				}
			}
			else
			{
				byte[] array2 = data;
				foreach (byte b in array2)
				{
					sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
				}
			}
			return pre + sb.ToString().ToUpper().Trim();
		}
		catch (Exception ex)
		{
			
			return null;
		}
	}

    public static byte[] BinaryToHex(byte[] binaryBytes)
    {
        int hexLength = binaryBytes.Length / 8;
        byte[] hexBytes = new byte[hexLength];

        for (int i = 0; i < hexLength; i++)
        {
            byte hexByte = 0;

            for (int j = 0; j < 8; j++)
            {
                byte binaryBit = binaryBytes[i * 8 + j];
                hexByte = (byte)((hexByte << 1) | binaryBit);
            }

            hexBytes[i] = hexByte;
        }

        return hexBytes;
    }

    public static string ToHex(this byte[] data, bool isWithSpace = false, string pre = null, bool isReverse = false)
	{
		if (data == null || data.Length < 1)
		{
			return null;
		}
		try
		{
			if (isReverse)
			{
				data = data.Reverse().ToArray();
			}
			StringBuilder sb = new StringBuilder(data.Length * 2);
			if (isWithSpace)
			{
				byte[] array = data;
				foreach (byte b2 in array)
				{
					sb.Append(Convert.ToString(b2, 16).PadLeft(2, '0').PadLeft(3, ' '));
				}
			}
			else
			{
				byte[] array2 = data;
				foreach (byte b in array2)
				{
					sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
				}
			}
			return pre + sb.ToString().ToUpper().Trim();
		}
		catch (Exception ex)
		{
			
			return null;
		}
	}

	public static string ToStr(this byte[] data, Encoding encoding = null)
	{
		if (data == null || data.Length < 1)
		{
			return null;
		}
		try
		{
			return (encoding == null) ? Encoding.UTF8.GetString(data) : encoding.GetString(data);
		}
		catch (Exception ex)
		{
			
			return null;
		}
	}

	public static byte[] IntToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			int temp = Convert.ToInt32(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] IntToBytes(this int value)
	{
		return BitConverter.GetBytes(value);
	}

	public static int ToInt(this byte[] bytes)
	{
		if (bytes == null || bytes.Length < 4)
		{
			return 0;
		}
		return BitConverter.ToInt32(bytes, 0);
	}

	public static int ToInt(this byte[] bytes, int index)
	{
		if (bytes == null || bytes.Length < 4 || index < 0 || index + 4 > bytes.Length)
		{
			return 0;
		}
		byte[] result = new byte[4];
		Array.Copy(bytes, index, result, 0, 4);
		return BitConverter.ToInt32(result, 0);
	}

	public static byte[] UintToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			uint temp = Convert.ToUInt32(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] UintToBytes(this uint value)
	{
		return BitConverter.GetBytes(value);
	}

	public static uint ToUint(this byte[] bytes)
	{
		if (bytes == null || bytes.Length < 4)
		{
			return 0u;
		}
		return BitConverter.ToUInt32(bytes, 0);
	}

	public static uint ToUint(this byte[] bytes, int index)
	{
		if (bytes == null || index < 0 || index + 4 > bytes.Length)
		{
			return 0u;
		}
		byte[] result = new byte[4];
		Array.Copy(bytes, index, result, 0, 4);
		return BitConverter.ToUInt32(result, 0);
	}

	public static byte[] ShortToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			short temp = Convert.ToInt16(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] ShortToBytes(this short value)
	{
		return BitConverter.GetBytes(value);
	}

	public static short ToShort(this byte[] bytes)
	{
		if (bytes == null || bytes.Length < 2)
		{
			return 0;
		}
		return BitConverter.ToInt16(bytes, 0);
	}

	public static short ToShort(this byte[] bytes, int index)
	{
		if (bytes == null || bytes.Length < 2 || index < 0 || index + 2 > bytes.Length)
		{
			return 0;
		}
		byte[] result = new byte[2];
		Array.Copy(bytes, index, result, 0, 2);
		return BitConverter.ToInt16(result, 0);
	}

	public static byte[] UshortToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			ushort temp = Convert.ToUInt16(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] UshortToBytes(this ushort value, bool isReverse = false)
	{
		byte[] result = BitConverter.GetBytes(value);
		if (isReverse)
		{
			Array.Reverse(result);
		}
		return result;
	}

	public static ushort ToUshort(this byte[] bytes)
	{
		if (bytes == null || bytes.Length < 2)
		{
			return 0;
		}
		return BitConverter.ToUInt16(bytes, 0);
	}

	public static ushort ToUshort(this byte[] bytes, int index)
	{
		if (bytes == null || bytes.Length < 2 || index < 0 || index + 2 > bytes.Length)
		{
			return 0;
		}
		byte[] result = new byte[2];
		Array.Copy(bytes, index, result, 0, 2);
		return BitConverter.ToUInt16(result, 0);
	}

	public static byte[] FloatToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			float temp = Convert.ToSingle(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] FloatToBytes(this float value)
	{
		return BitConverter.GetBytes(value);
	}

	public static float ToFloat(this byte[] bytes, bool isReverse = false)
	{
		if (isReverse && bytes != null)
		{
			Array.Reverse(bytes);
		}
		return (bytes == null) ? 0f : BitConverter.ToSingle(bytes, 0);
	}

	public static float ToFloat(this byte[] bytes, int index)
	{
		if (bytes == null || bytes.Length < 4 || index < 0 || index + 4 > bytes.Length)
		{
			return 0f;
		}
		byte[] result = new byte[4];
		Array.Copy(bytes, index, result, 0, 4);
		return BitConverter.ToSingle(result, 0);
	}

	public static byte[] DoubleToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			double temp = Convert.ToDouble(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] DoubleToBytes(this double value)
	{
		return BitConverter.GetBytes(value);
	}

	public static double ToDouble(this byte[] bytes)
	{
		return BitConverter.ToDouble(bytes, 0);
	}

	public static double ToDouble(this byte[] bytes, int index)
	{
		if (bytes == null || bytes.Length < 8 || index < 0 || index + 8 > bytes.Length)
		{
			return 0.0;
		}
		byte[] result = new byte[8];
		Array.Copy(bytes, index, result, 0, 8);
		return BitConverter.ToDouble(result, 0);
	}

	public static byte[] LongToBytes(this object value)
	{
		if (value == null)
		{
			return null;
		}
		try
		{
			long temp = Convert.ToInt64(value);
			return BitConverter.GetBytes(temp);
		}
		catch
		{
			return null;
		}
	}

	public static byte[] LongToBytes(this long value)
	{
		return BitConverter.GetBytes(value);
	}

	public static long ToLong(this byte[] bytes)
	{
		return (bytes == null) ? 0 : BitConverter.ToInt64(bytes, 0);
	}

	public static byte[] ToBytes(this BitArray value)
	{
		if (value == null || value.Length == 0)
		{
			return null;
		}
		int conutBase = value.Length / 8;
		int mod = ((value.Length % 8 != 0) ? 1 : 0);
		byte[] result = new byte[conutBase + mod];
		value.CopyTo(result, 0);
		return result;
	}

	public static BitArray ToBitArray(this byte[] bytes)
	{
		if (bytes == null || bytes.Length == 0)
		{
			return null;
		}
		return new BitArray(bytes);
	}

	public static byte ToByte(this BitArray value)
	{
		if (value == null || value.Length == 0)
		{
			return 0;
		}
		int conutBase = value.Length / 8;
		int mod = ((value.Length % 8 != 0) ? 1 : 0);
		byte[] result = new byte[conutBase + mod];
		value.CopyTo(result, 0);
		return result[0];
	}

	public static BitArray ToBitArray(this byte data)
	{
		return new BitArray(new byte[1] { data });
	}

	public static byte[] GetBits(this byte[] oriData, byte index, byte bitCount)
	{
		if (oriData == null || bitCount > oriData.Length * 8)
		{
			return null;
		}
		BitArray sourceArray = oriData.ToBitArray();
		BitArray targetArray = new BitArray(bitCount);
		for (byte i = 0; i < bitCount; i++)
		{
			targetArray[i] = sourceArray[index + i];
		}
		return targetArray.ToBytes();
	}

	public static byte[] SetBits(this byte[] oriData, byte index, byte bitCount, byte[] data)
	{
		if (oriData == null)
		{
			return null;
		}
		if (data == null || index + bitCount > oriData.Length * 8 || bitCount > data.Length * 8)
		{
			return oriData;
		}
		BitArray sourceArray = data.ToBitArray();
		BitArray targetArray = oriData.ToBitArray();
		for (byte i = 0; i < bitCount; i++)
		{
			targetArray[index + i] = sourceArray[i];
		}
		return targetArray.ToBytes();
	}

	public static byte GetBits(this byte oriData, byte index, byte bitCount)
	{
		if (bitCount == 0 || index + bitCount > 8)
		{
			return 0;
		}
		BitArray sourceArray = oriData.ToBitArray();
		BitArray targetArray = new BitArray(bitCount);
		for (byte i = 0; i < bitCount; i++)
		{
			targetArray[i] = sourceArray[index + i];
		}
		return targetArray.ToByte();
	}

	public static byte SetBits(this byte oriData, byte index, byte bitCount, byte data)
	{
		if (bitCount == 0 || index + bitCount > 8)
		{
			return oriData;
		}
		BitArray sourceArray = data.ToBitArray();
		BitArray targetArray = oriData.ToBitArray();
		for (byte i = 0; i < bitCount; i++)
		{
			targetArray[index + i] = sourceArray[i];
		}
		return targetArray.ToByte();
	}

	public static void SetBitHigh(this byte[] source, byte byteIndex, byte bitIndex, bool isHigh = true)
	{
		if (source != null && source.Length > byteIndex && bitIndex <= 7)
		{
			byte data = source[byteIndex];
			data = ((!isHigh) ? ((byte)(data & (byte)(~(1 << (int)bitIndex)))) : ((byte)(data | (byte)(1 << (int)bitIndex))));
			source[byteIndex] = data;
		}
	}

	public static bool BitHigh(this byte[] source, byte byteIndex, byte bitIndex)
	{
		if (source == null || source.Length <= byteIndex || bitIndex > 7)
		{
			return false;
		}
		return (source[byteIndex] & (1 << (int)bitIndex)) != 0;
	}

	public static byte SetBitHigh(this byte data, byte i, bool isHigh = true)
	{
		if (i > 7)
		{
			return data;
		}
		if (isHigh)
		{
			return data |= (byte)(1 << (int)i);
		}
		return data &= (byte)(~(1 << (int)i));
	}

	public static bool BitHigh(this byte data, byte i)
	{
		return i <= 7 && (data & (1 << (int)i)) != 0;
	}

	public static double DataStandardize(this string str, int roundNum = 3)
	{
		if (string.IsNullOrEmpty(str))
		{
			return 0.0;
		}
		try
		{
			str = str.Replace("\r", "").Replace("\n", "").Replace(" ", "");
			if (string.IsNullOrEmpty(str))
			{
				return 0.0;
			}
			double val;
			if (str.Contains('E'))
			{
				string[] strArr = str.Split('E');
				string baseStr = strArr[0];
				double baseVal = Convert.ToDouble(baseStr);
				string powerStr = strArr[1];
				double powerVal = Convert.ToInt32(powerStr);
				val = Math.Pow(10.0, powerVal) * baseVal;
			}
			else
			{
				val = Convert.ToDouble(str);
			}
			return Math.Round(val, roundNum);
		}
		catch (Exception)
		{
			return 0.0;
		}
	}
}

字节数组与二进制相关转换

  • ToBinaryByteArray方法
    将输入的字节数组转换为表示其每一位的二进制字节数组,每个字节按位展开为8个二进制位存储在新的字节数组中。

  • BinaryArrayToDecimal方法
    把二进制字节数组转换为十进制整数,通过对二进制位对应的2的幂次进行累加来实现转换。

  • BinaryToHex方法
    将二进制字节数组转换为十六进制字节数组,按照一定的位运算规则将8位一组的二进制转换为十六进制表示。

不同数据类型与字节数组相互转换

  • 整数类型相关转换
    • IntToBytes(两个重载方法)
      • 可将int类型值或者object类型(实际能转换为int的对象)转换为字节数组,利用BitConverter.GetBytes方法来实现。
    • ToInt(两个重载方法)
      • 从字节数组中提取数据转换为int类型整数,根据字节数组长度及指定索引情况获取相应数据并转换。
    • UintToBytes(两个重载方法)
      • 针对无符号uint类型,能将uint值或可转换为uintobject转换为字节数组,同样借助BitConverter.GetBytes
    • ToUint(两个重载方法)
      • 把字节数组中的数据转换为无符号uint类型整数,考虑字节数组的合法性和索引范围进行转换。
  • 短整型相关转换
    • ShortToBytes(两个重载方法)
      • 可将short类型值或者能转换为shortobject转换为字节数组,使用BitConverter.GetBytes操作。
    • ToShort(两个重载方法)
      • 从字节数组中获取数据并转换为short类型整数,对字节数组的长度和索引做校验来确保转换正确。
    • UshortToBytes(两个重载方法)
      • 针对无符号ushort类型,能把ushort值或对应的object转换为字节数组,可选择是否反转字节顺序。
    • ToUshort(两个重载方法)
      • 将字节数组中的内容转换为无符号ushort类型整数,依据字节数组条件来执行转换。
  • 浮点型相关转换
    • FloatToBytes(两个重载方法)
      • float类型值或者可转换为floatobject转换为字节数组,借助BitConverter.GetBytes实现转换。
    • ToFloat(两个重载方法)
      • 从字节数组提取数据转换为float类型浮点数,支持根据是否反转字节顺序进行相应处理。
    • DoubleToBytes(两个重载方法)
      • 用于将double类型值或者能转换为doubleobject转换为字节数组,调用BitConverter.GetBytes
    • ToDouble(两个重载方法)
      • 从字节数组中获取数据并转换为double类型双精度浮点数,会校验字节数组长度和索引范围。
  • 长整型相关转换
    • LongToBytes(两个重载方法)
      • 可把long类型值或者可转换为longobject转换为字节数组,依靠BitConverter.GetBytes进行转换。
    • ToLong方法
      • 从字节数组中读取数据并转换为long类型长整数。

字节数组顺序相关转换

  • SwitchBytes方法
    按照指定的块大小(默认块大小为2)对字节数组中的数据块进行反转顺序操作,例如每2个字节一组进行反转。

  • BytesReverse方法
    直接对整个字节数组进行反转顺序的操作,返回反转后的字节数组。

字节数组与字符串相关转换

  • BytesToStr方法
    将字节数组转换为字符串,如果未指定编码则使用默认编码(Encoding.Default)进行转换,也可指定编码来转换。

  • StrToBytes方法
    把输入的字符串转换为字节数组,先对字符串做去除空白字符等预处理,若未指定编码则使用UTF8编码进行转换,否则按指定编码转换。

十六进制相关转换

  • HexToByte方法
    把十六进制表示的字符串(可包含或去除如0x、空格、换行、回车等格式相关字符)转换为字节类型,若转换失败则返回0。

  • ByteToHex方法
    将字节类型数据转换为十六进制表示的字符串,进行格式化为固定长度并转换为大写形式。

  • ToHex(多个重载方法)

    • 可将字节或字节数组转换为十六进制表示的字符串,支持添加前缀、是否带空格间隔以及是否反转字节顺序等多种格式控制。
  • HexToBytes(多个重载方法)

    • 能把十六进制表示的字符串或者对象(通过其ToString方法后的字符串)转换为字节数组,可选择是否反转字节顺序,处理各种字符串格式异常情况。

布尔值与十六进制、二进制相关转换

  • HexToBoolBinary方法
    将十六进制字节数组转换为布尔值数组,先把十六进制字节按位转换为二进制字节,再进一步转换为布尔值数组(0对应false,1对应true)。

位操作相关转换

  • ToBitArray(两个重载方法)
    • 可将字节数组或者字节类型数据转换为BitArray类型,用于后续的位操作相关处理。
    • 从字节数组或单个字节创建对应的BitArray实例。
  • ToBytes(两个重载方法)
    • BitArray类型数据转换为字节数组,根据BitArray的长度情况进行字节数组的构建与赋值。
    • BitArray获取字节数组表示,考虑长度是否为8的倍数等情况。
  • GetBits(多个重载方法)
    • 从字节数组或者单个字节中按照指定的起始位索引和获取的位数,提取相应的位数据并转换为字节数组或字节类型返回。
  • SetBits(多个重载方法)
    • 对字节数组或者单个字节在指定的起始位索引和位数范围内,用给定的数据设置相应的位,返回更新后的字节数组或字节类型。
  • SetBitHigh(多个重载方法)
    • 针对字节数组或者单个字节,可设置指定字节位置和位索引处的位为高电平(置1)或低电平(置0),并返回更新后的字节数组或字节类型。
  • BitHigh(多个重载方法)
    • 检查字节数组或者单个字节在指定字节位置和位索引处的位是否为高电平(即是否为1),返回布尔值表示结果。

数据标准化相关转换

  • DataStandardize方法
    对输入的字符串进行处理,去除空白字符等,将科学计数法表示或普通数字表示的字符串转换为标准化的双精度浮点数,可指定保留的小数位数进行四舍五入。

二维数组行列转换相关转换

  • ConvertRowMajorToColumnMajor方法
    将按行优先顺序排列的可枚举元素集合转换为按列优先顺序排列的集合,需要指定行数和列数来进行转换操作,返回转换后的列优先顺序的集合。

网站公告

今日签到

点亮在社区的每一天
去签到