namespace Systempublic static class ConvertExtension
{public static byte[] ToBinaryByteArray(this byte[] bytes){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
值或可转换为uint
的object
转换为字节数组,同样借助BitConverter.GetBytes
。
ToUint
(两个重载方法): - 把字节数组中的数据转换为无符号
uint
类型整数,考虑字节数组的合法性和索引范围进行转换。
- 短整型相关转换
ShortToBytes
(两个重载方法): - 可将
short
类型值或者能转换为short
的object
转换为字节数组,使用BitConverter.GetBytes
操作。
ToShort
(两个重载方法): - 从字节数组中获取数据并转换为
short
类型整数,对字节数组的长度和索引做校验来确保转换正确。
UshortToBytes
(两个重载方法): - 针对无符号
ushort
类型,能把ushort
值或对应的object
转换为字节数组,可选择是否反转字节顺序。
ToUshort
(两个重载方法): - 将字节数组中的内容转换为无符号
ushort
类型整数,依据字节数组条件来执行转换。
- 浮点型相关转换
FloatToBytes
(两个重载方法): - 把
float
类型值或者可转换为float
的object
转换为字节数组,借助BitConverter.GetBytes
实现转换。
ToFloat
(两个重载方法): - 从字节数组提取数据转换为
float
类型浮点数,支持根据是否反转字节顺序进行相应处理。
DoubleToBytes
(两个重载方法): - 用于将
double
类型值或者能转换为double
的object
转换为字节数组,调用BitConverter.GetBytes
。
ToDouble
(两个重载方法): - 从字节数组中获取数据并转换为
double
类型双精度浮点数,会校验字节数组长度和索引范围。
- 长整型相关转换
LongToBytes
(两个重载方法): - 可把
long
类型值或者可转换为long
的object
转换为字节数组,依靠BitConverter.GetBytes
进行转换。
ToLong
方法:
字节数组顺序相关转换
字节数组与字符串相关转换
十六进制相关转换
布尔值与十六进制、二进制相关转换
HexToBoolBinary
方法:
将十六进制字节数组转换为布尔值数组,先把十六进制字节按位转换为二进制字节,再进一步转换为布尔值数组(0对应false
,1对应true
)。
位操作相关转换
ToBitArray
(两个重载方法): - 可将字节数组或者字节类型数据转换为
BitArray
类型,用于后续的位操作相关处理。 - 从字节数组或单个字节创建对应的
BitArray
实例。
ToBytes
(两个重载方法): - 把
BitArray
类型数据转换为字节数组,根据BitArray
的长度情况进行字节数组的构建与赋值。 - 从
BitArray
获取字节数组表示,考虑长度是否为8的倍数等情况。
GetBits
(多个重载方法): - 从字节数组或者单个字节中按照指定的起始位索引和获取的位数,提取相应的位数据并转换为字节数组或字节类型返回。
SetBits
(多个重载方法): - 对字节数组或者单个字节在指定的起始位索引和位数范围内,用给定的数据设置相应的位,返回更新后的字节数组或字节类型。
SetBitHigh
(多个重载方法): - 针对字节数组或者单个字节,可设置指定字节位置和位索引处的位为高电平(置1)或低电平(置0),并返回更新后的字节数组或字节类型。
BitHigh
(多个重载方法): - 检查字节数组或者单个字节在指定字节位置和位索引处的位是否为高电平(即是否为1),返回布尔值表示结果。
数据标准化相关转换
DataStandardize
方法:
对输入的字符串进行处理,去除空白字符等,将科学计数法表示或普通数字表示的字符串转换为标准化的双精度浮点数,可指定保留的小数位数进行四舍五入。
二维数组行列转换相关转换
ConvertRowMajorToColumnMajor
方法:
将按行优先顺序排列的可枚举元素集合转换为按列优先顺序排列的集合,需要指定行数和列数来进行转换操作,返回转换后的列优先顺序的集合。