C# string和ushort数组互相转换
最近采用Nmodbus里的modbus协议模块与plc通讯,模块里都是发送ushort数据,项目要求发送字符串,因此需要转换,查了一些网上的代码,有些有错误,自己整理修改一下在此分享,高手勿喷。`在这里插入代码片`
//string类型转化为ushort数组public ushort[] stringToUshort(String inString){if (inString.Length % 2 == 1) { inString += " "; }char[] bufChar = inString.ToCharArray();byte[] outByte = new byte[bufChar.Length];byte[] bufByte = new byte[2];ushort[] outShort = new ushort[bufChar.Length / 2];for (int i = 0, j = 0; i < bufChar.Length; i += 2, j++){bufByte[0] = BitConverter.GetBytes(bufChar[i])[0];bufByte[1] = BitConverter.GetBytes(bufChar[i+1])[0];outShort[j] = BitConverter.ToUInt16(bufByte, 0); }return outShort;}//ushort数组转化为stringpublic string ushortToString(ushort[] inUshort){byte[] outByte = new byte[inUshort.Length*2];for (int i = 0; i < inUshort.Length; i++){byte[] bufByte= BitConverter.GetBytes(inUshort[i]);outByte[i*2] = bufByte[0];outByte[i*2+1] = bufByte[1];}string str = ASCIIEncoding.ASCII.GetString(outByte).Trim();return str;}
C# string和ushort数组互相转换相关推荐
- C# String 与 Ushort[] 数组 相互转换
String To Ushort[] 数组输出 思路: string -> char[] -> byte[] -> byte[2] -> ushort -> us ...
- CString,string,char数组的转换
虽然网上关于CString,string,char数组的转换的文章一大堆,但是感觉很乱很杂,而且许多并不能真正达到目的,在此,我把自己调试通过的转换方法贴到这里,做个笔记. 编译环境:vs2008, ...
- Java char转换为String,String转换为char数组
Today we will look into java char to String program. We will also learn how to convert String to a c ...
- String与字节数组转换
字节数组–>字符串 String(byte[]): 通过使用平台的默认字符集解码指定的byte数组,构造一个新的String String(byte[],int offset,int lengt ...
- Java springboot Object转换List String转List 数组转List
以下是Object转List的需求场景 前端通过http请求,body以json形式,内容含有字符串.数组. 后端使用Map<string,Object>的方式接收,些时如何将部分的Obj ...
- String构造方法和字符集编码转换
2019独角兽企业重金招聘Python工程师标准>>> 声明:本栏目所使用的素材都是凯哥学堂VIP学员所写,学员有权匿名,对文章有最终解释权:凯哥学堂旨在促进VIP学员互相学习的基础 ...
- C# string 和byte[]之间的转换
c#将string和byte数组之间互相转换 如下方法将字符串转换为byte数组,使用System.Buffer.BlockCopy方法. static byte[] GetBytes(strin ...
- Java中List与数组互相转换
1.说明 在Java中,经常遇到需要List与数组互相转换的场景. List转换成数组,可以使用List的toArray()或者toArray(T[] a)方法. 数组转换成List,可以使用Arra ...
- 集合 数组 定义 转换 遍历 Arrays API MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
最新文章
- 小程序直播间页面路径怎么访问直播间_以小程序为例,在线教育产品的直播间有哪些功能设计?...
- 学习响应式BootStrap来写融职教育网站,Bootsrtap第九天手粉琴swiper特效
- C#使用Cookie方法
- 人工智能时代,决定未来的3个问题
- 后台模板 开源_3个开源样板网页设计模板
- 前端开发工具介绍----合成雪碧图工具(css sprite)
- 算法的基本控制结构之循环结构
- linux 6.5 :qw,rhel 6.5替换centOS6的网易yum源
- 定量论文:探究「健康水平、婚姻状况」对幸福感的影响
- What is the Actual Performance of HANA?
- NumberFormat格式化数字
- 3:AngularJS:模糊查询过滤内容,下拉菜单排序,过滤敏感字符,验证判断后添加表格信息
- ajax hapi上传文件,在hapi框架里使用ajax提交表单数据,但是服务端接收到的数据是空对象。怎么办啊?...
- AUTOCAD——弧长标注命令、半径标注命令
- 控制工程中的数学建模(3)——自动控制系统的一般模型
- 一生应该必看的20个故事
- 《南方有乔木》:陈伟霆、白百何带你玩转“黑科技”无人机和VR虚拟现实
- 升级windows11后wireshark显示wireshark Can‘t get list of interfaces: PacketGetAdapterNames报错
- KU115 PCIE总线数据预处理板卡(多LVDS接口)
- 【python】牛顿迭代法求解多元函数的最小值--以二元函数为例