using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IStation.DataDockingSocket
{
internal class ByteMsgHelper
{
///
/// 字符串转16进制字符2
///
/// 字符串
/// 编码格式
///
public static List StringToHexValuve(string content, out string error_info)
{
//去掉空格
string[] arr = content.Split(' ');
if (arr.Length < 3)
{
arr = content.Split('-');
if (arr.Length < 3)
{
error_info = "字符无法解析";
return null;
}
}
List result = new List();
for (int i = 0; i < arr.Length; i++)
{
if (string.IsNullOrWhiteSpace(arr[i]))
continue;
var dddd = Convert.ToByte(arr[i], 16);
result.Add(dddd);
}
error_info = null;
return result;
}
#region 数据转化
public static int GetInt2Byte(byte[] byteMessage, int startPosition, out string info)
{
byte[] value = new byte[2];
Array.Copy(byteMessage, startPosition, value, 0, 2);
info = BitConverter.ToString(value, 0, value.Length);
// ushort rValueP = BitConverter.ToUInt16(value.Reverse().ToArray(), 0);
//short rValueP = 0;
//rValueP = byteMessage[ startPosition];
//rValueP <<= 8;
//rValueP += byteMessage[ startPosition + 1];
//return rValueP;
return bytesToInt2(byteMessage, startPosition);
}
public static int GetInt4Byte(byte[] byteMessage, int startPosition, out string info)
{
byte[] value = new byte[4];
Array.Copy(byteMessage, startPosition, value, 0, 4);
info = BitConverter.ToString(value, 0, value.Length);
// ushort rValueP = BitConverter.ToUInt16(value.Reverse().ToArray(), 0);
//short rValueP = 0;
//rValueP = byteMessage[ startPosition];
//rValueP <<= 8;
//rValueP += byteMessage[ startPosition + 1];
//return rValueP;
return bytesToInt4(byteMessage, startPosition);
}
/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
*
* @param src
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/
public static int bytesToInt2_LH(byte[] src, int offset)
{
int value;
value = src[offset] & 0xFF
| (src[offset + 1] & 0xFF) << 8;
return value;
}
/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。2个字节
*/
public static int bytesToInt2(byte[] src, int offset)
{
int value;
value =
(src[offset + 0] & 0xFF) << 8
| src[offset + 1] & 0xFF;
return value;
}
/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。4个字节
*/
public static int bytesToInt4(byte[] src, int offset = 0)
{
int value;
value = (src[offset] & 0xFF) << 24
| (src[offset + 1] & 0xFF) << 16
| (src[offset + 2] & 0xFF) << 8
| src[offset + 3] & 0xFF;
return value;
}
public static double GetDouble1(byte[] byteMessage, int startPosition, out string info)
{
byte[] value = new byte[4];
Array.Copy(byteMessage, startPosition, value, 0, 4);
info = BitConverter.ToString(value, 0, value.Length);
//return BitConverter.ToDouble(byteMessage, startPosition);
return BitConverter.ToSingle(value.Reverse().ToArray(), 0);//采用了IEEE-754二进制浮点数算术标准
}
#endregion
}
}