C#short 、ushort、 byte、 byte[]转换分析

关键字:

1.C#数据类型转换

2.short转byte

3.modbus通信解析

之前有写过modbus通信,对数据处理这块做个回顾,因为使用了第三方库,返回数据是ushort[],在这摸索一下其他的数据转换知识,modbus rtu 通信链接:http://t.csdnimg.cn/zR8Ug

下面贴出测试代码,配合注释参考:

        static void Main(string[] args)
		{
			ushort[] data = { 30};
			ushort[] data2 = { 3002 };

			Console.WriteLine("Hello, World!");
			byte[] b2 = new byte[] { 0x12, 0x11 };

			//下面两句是判断字节数组转ushort的方法
			//注意下面结果输出一致,自带反转可能是因为BitConverter.IsLittleEndian结果为true?
			Console.WriteLine(BitConverter.ToInt16(b2));
			Console.WriteLine(ByteArrayToReverseHexString(b2));

			//下面是判断ushort数组转字节数组的方法
			//ushort数组直接转字节数组
			//byte最大表示到2^8,这里3002太大就会报错,小于256的数可以转换,因为Array.ConvertAll转换前后保持个数一致?
			byte[] byteArray = Array.ConvertAll<ushort, byte>(data, Convert.ToByte);
			//先转16进制字符串再转字节数组
			var bytesByHex = HexStringToByteArray(data[0].ToString("X4"));
			//查看结果是否一致
			Console.WriteLine(Enumerable.SequenceEqual(byteArray, bytesByHex));

			//下面是ushort与字节数组互转的方法
			var bytes = ShortToByte((short)data[0]);
			var sValue = ByteToShort(bytes);
		}
		/// <summary>
		/// Byte[] Reverse 2 Hex
		/// </summary>
		/// <param name="bytes"></param>
		/// <returns></returns>
		public static int ByteArrayToReverseHexString(byte[] bytes)
		{
			if (bytes.Length > 0)
			{
				var byteTemp = ReverseByteArray(bytes);
				//hex
				var hex =  BitConverter.ToString(byteTemp).Replace("-", "");
				return Convert.ToInt32(hex, 16);

			}
			return -1;
		}
		/// <summary>
		/// 数组倒序排列
		/// </summary>
		/// <param name="elements">数组参数</param>
		/// <returns></returns>
		public static T[] ReverseByteArray<T>(T[] elements)
		{
			if (elements.Length > 0)
			{
				var left = 0;
				var right = elements.Length - 1;
				while (left < right)
				{
					(elements[left], elements[right]) = (elements[right], elements[left]);
					left++;
					right--;
				}
			}
			return elements;
		}
		/// <summary>
		/// Hex 2 Byte[]
		/// </summary>
		/// <param name="hexString"></param>
		/// <returns></returns>
		/// <exception cref="ArgumentException"></exception>
		public static byte[] HexStringToByteArray(string hexString)
		{
			try
			{
				if (hexString == null || hexString.Length % 2 != 0)
				{
					throw new ArgumentException("无效的16进制字符串");
				}
				byte[] bytes = new byte[hexString.Length / 2];
				for (int i = 0; i < hexString.Length; i += 2)
				{
					bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
				}
				return bytes;
			}
			catch (Exception e)
			{
				return null;
			}


		}
		/// <summary>
		/// Short2Byte
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static byte[] ShortToByte(short value)
		{
			return BitConverter.GetBytes(value);
		}
		/// <summary>
		/// Byte2Short
		/// </summary>
		/// <param name="arr"></param>
		/// <returns></returns>
		public static short ByteToShort(byte[] arr)
		{
			return BitConverter.ToInt16(arr, 0);
		}
		
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用海康提供的 SDK (如 HCNetSDK 或者 EZ_SDK) 来播放海康的 MP4 视频。以下是一些示例代码,用于在 C# 中使用 HCNetSDK 播放海康 MP4 视频: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace HCNetSDKTest { public partial class Form1 : Form { // HCNetSDK.dll 的路径 const string HCNetSDKDllPath = "HCNetSDK.dll"; // 登录句柄 private int iLoginID = -1; // 播放句柄 private int iPlayID = -1; // 播放窗口 private IntPtr hWnd; // SDK 初始化 [DllImport(HCNetSDKDllPath)] private static extern bool NET_DVR_Init(); // SDK 释放 [DllImport(HCNetSDKDllPath)] private static extern bool NET_DVR_Cleanup(); // 用户登录 [DllImport(HCNetSDKDllPath)] private static extern int NET_DVR_Login_V30(string sDVRIP, ushort wDVRPort, string sUserName, string sPassword, ref NET_DVR_DEVICEINFO_V30 lpDeviceInfo); // 用户注销 [DllImport(HCNetSDKDllPath)] private static extern bool NET_DVR_Logout(int iLoginID); // 打开实时预览 [DllImport(HCNetSDKDllPath)] private static extern int NET_DVR_RealPlay_V40(int iUserID, ref NET_DVR_PREVIEWINFO lpPreviewInfo, REALDATACALLBACK fRealDataCallback_V30, IntPtr pUser); // 关闭预览 [DllImport(HCNetSDKDllPath)] private static extern bool NET_DVR_StopRealPlay(int iPlayHandle); // 视频数据回调函数 public delegate void REALDATACALLBACK(int lRealHandle, uint dwDataType, IntPtr pBuffer, uint dwBufSize, IntPtr pUser); // 预览参数结构体 public struct NET_DVR_PREVIEWINFO { public int lChannel; public uint dwStreamType; public uint dwLinkMode; public IntPtr hPlayWnd; public uint bBlocked; public uint bPassbackRecord; public uint byPreviewMode; public uint byStreamID; public byte[] byReserve; } // 设备信息结构体 [StructLayout(LayoutKind.Sequential)] public struct NET_DVR_DEVICEINFO_V30 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)] public string sSerialNumber; public byte byAlarmInPortNum; public byte byAlarmOutPortNum; public byte byDiskNum; public byte byDVRType; public byte byChanNum; public byte byStartChan; public byte byAudioChanNum; public byte byIPChanNum; public byte byZeroChanNum; public byte byMainProto; public byte bySubProto; public byte bySupport; public byte bySupport1; public byte byRes1; public short wDevType; public byte byRes2; public byte bySupport2; public ushort wFirmwareVersion; public ushort wNetProtoVersion; public ushort wUserProtoVersion; public ushort wSignalVersion; public ushort wIrdaVersion; public byte byRes3; public byte byHardwareVersion; public byte bySoftwareVersion; public byte byMiddleWareVersion; public byte byBuildDate; public byte byModifyDate; public byte byRes4; public byte byDevicePerformanceLevel; public byte byReserve2; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // SDK 初始化 NET_DVR_Init(); // 获取播放窗口句柄 hWnd = pictureBox1.Handle; // 登录 NET_DVR_DEVICEINFO_V30 devInfo = new NET_DVR_DEVICEINFO_V30(); iLoginID = NET_DVR_Login_V30("192.168.1.64", 8000, "admin", "12345", ref devInfo); // 设置预览参数 NET_DVR_PREVIEWINFO previewInfo = new NET_DVR_PREVIEWINFO(); previewInfo.lChannel = 1; // 通道号 previewInfo.dwStreamType = 0; // 码流类型:0-主码流,1-子码流,2-码流3,3-码流4,以此类推 previewInfo.dwLinkMode = 0; // 连接模式:0-TCP,1-UDP,2-多播,3-RTP,4-RTP/RTSP,5-RSTP/HTTP previewInfo.hPlayWnd = hWnd; // 播放窗口句柄 previewInfo.bBlocked = 1; // 阻塞取流:1-是,0-否 previewInfo.byPreviewMode = 0; // 预览模式:0-正常预览,1-延迟预览 previewInfo.byPassbackRecord = 0; // 是否启用录像回传:0-不启用,1-启用 previewInfo.byStreamID = 1; // 码流ID,取值范围为从0开始的32个整数 previewInfo.byReserve = new byte[216]; // 保留字段 // 打开实时预览 iPlayID = NET_DVR_RealPlay_V40(iLoginID, ref previewInfo, null, IntPtr.Zero); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // 关闭预览 NET_DVR_StopRealPlay(iPlayID); // 注销 NET_DVR_Logout(iLoginID); // SDK 释放 NET_DVR_Cleanup(); } } } ``` 请注意,上述示例代码仅提供了基本的播放功能,并没有进行错误处理和异常处理。在实际应用中,您需要根据具体情况进行完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值