C# 将结构体转为字节流的方式
1、 将基础类型转为byte数组存储
private byte[] CreateNetDataByteStream(ushort system, ushort host, ushort type, byte[] tx_buf, ushort msg_len, ushort flag)
{
if (tx_buf == null)
{
return null;
}
try
{
byte[] data = new byte[msg_len + NetDataHeadLen];
byte[] u16byte = new byte[];
u16byte = BitConverter.GetBytes(type);
Array.Copy(u16byte, , data, , );
u16byte = BitConverter.GetBytes(flag);
Array.Copy(u16byte, , data, , );
u16byte = BitConverter.GetBytes(msg_len);
Array.Copy(u16byte, , data, , );
// u16byte = BitConverter.GetBytes(CommonConstant.MySystemID);
Array.Copy(u16byte, , data, , );
// u16byte = BitConverter.GetBytes((ushort)CommonConstant.MySeatName);
Array.Copy(u16byte, , data, , );
u16byte = BitConverter.GetBytes(system);
Array.Copy(u16byte, , data, , );
u16byte = BitConverter.GetBytes(host);
Array.Copy(u16byte, , data, , );
tx_buf.CopyTo(data, NetDataHeadLen);
return data;
}
catch
{
return null;
}
}
2.C#中结构体 与 字节流 相互转化
方式一
//将一个结构序列化为字节数组
private IFormatter formatter = new BinaryFormatter();
private ValueType deserializeByteArrayToInfoObj(byte[] bytes)
{
ValueType vt;
if (bytes == null || bytes.Length == )
{
return null;
} try
{
MemoryStream stream = new MemoryStream(bytes);
stream.Position = ;
stream.Seek(, SeekOrigin.Begin);
vt = (ValueType)formatter.Deserialize(stream);
stream.Close();
return vt;
}
catch (Exception ex)
{
return null;
}
}
//将一个结构序列化为字节数组
private byte[] serializeInfoObjToByteArray(ValueType infoStruct)
{
if (infoStruct == null)
{
return null;
} try
{
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, infoStruct); byte[] bytes = new byte[(int)stream.Length];
stream.Position = ;
int count = stream.Read(bytes, , (int)stream.Length);
stream.Close();
return bytes;
}
catch (Exception ex)
{
return null;
}
}
方式二
/// <summary>
/// 将字节数组转换为结构体
/// </summary>
/// <param name="bytes"></param>
/// <param name="type"></param>
/// <returns></returns>
public object ByteaToStruct(byte[] bytes, Type type)
{
//得到结构体大小
int size = Marshal.SizeOf(type);
Math.Log(size, ); if (size > bytes.Length)
return null;
//分配结构大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将BYTE数组拷贝到分配好的内存空间
Marshal.Copy(bytes, , structPtr, size);
//将内存空间转换为目标结构
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内容空间
Marshal.FreeHGlobal(structPtr);
return obj;
}
/// <summary>
/// 将结构转换为字节数组
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public byte[] StructTOBytes(object obj)
{
int size = Marshal.SizeOf(obj);
//创建byte数组
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷贝到分配好的内存空间
Marshal.StructureToPtr(obj, structPtr, false);
//从内存空间拷贝到byte数组
Marshal.Copy(structPtr, bytes,, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
return bytes;
}
3. C# 结构体字节对齐
[structLayout(Layoutkind.sequential,charset=charset.ansi)]
Struct Mystruct
{
[MarshalAs(UnmanagedType.ByValArray,sizeConst=)]
Public byte[] serial;
Public byte Type;
Public uint Sum;
}
在上述结构体与字节流转换第二种方法中,获取结构体长度int size = Marshal.SizeOf(Mystruct);,并不是13,而是16。在内存特定类型数据结构起始地址通常有一定的对齐要求,比如32位机器的int起始地址必须是4的整数倍,结构通常也如此
需要添加[structLayout(Layoutkind.sequential,charset=charset.ansi,pack=1)]
C# 将结构体转为字节流的方式的更多相关文章
- 使用unsafe.Pointer将结构体转为[]byte
package main import ( "fmt" "unsafe" ) type TestStructTobytes struct { data int6 ...
- C#中结构体与字节流互相转换
1.定义与C++对应的C#结构体 在c#中的结构体不能定义指针,不能定义字符数组,只能在里面定义字符数组的引用. C++的消息结构体如下: //消息格式 4+16+4+4= 28个字节 struct ...
- c#结构体和字节流之间的相互转换
结构体转byte数组 1 首先要明白 ,是 在那个命名空间下 System.Runtime.InteropServices; 2 首先得到结构体的大小 2 开辟相应的内存空间 3 将结构体填 ...
- 使用xorm将结构体转为sql文件
操作步骤 (1)定义结构体 type User struct { Id int //表id Name string //姓名 ...}12345(2)编写代码,执行自动增量同步(mysql为例) im ...
- C++结构体对象数组的二进制方式读写
以一个学生信息的结构体数组为例. #include<iostream>#include<string>#include<fstream>using namespac ...
- C#中结构体定义并转换字节数组
最近的项目在做socket通信报文解析的时候,用到了结构体与字节数组的转换:由于客户端采用C++开发,服务端采用C#开发,所以双方必须保证各自定义结构体成员类型和长度一致才能保证报文解析的正确性,这一 ...
- C# 结构体定义 转换字节数组 z
客户端采用C++开发,服务端采用C#开发,所以双方必须保证各自定义结构体成员类型和长度一致才能保证报文解析的正确性. [StructLayoutAttribute(LayoutKind.Sequent ...
- GO学习-(38) Go语言结构体转map[string]interface{}的若干方法
结构体转map[string]interface{}的若干方法 本文介绍了Go语言中将结构体转成map[string]interface{}时你需要了解的"坑",也有你需要知道的若 ...
- p/invoke碎片,对结构体的处理
结构体的一些相关知识 可直接转换类类型,比如int类型,在托管代码和非托管代码中占据内存大小 和意义都是一个样的. 结构体封送的关键是:在托管代码和非托管代码中定义的一致性.什么是定义的一致性?包括结 ...
随机推荐
- mybatis源码阅读-执行一个sql的流程(九)
图解 图片来源:https://my.oschina.net/zudajun/blog/670373 Mapper接口调用原理 我们整合成Spring 直接使用Mapper就能执行对应的sql 表现 ...
- h5dnd sortable mutil groups
h5dnd sortable mutil groups https://codepen.io/webgeeker/pen/JmPXaN https://codepen.io/webgeeker/pen ...
- 20180725利用pmm监控管理mysql
转自:https://www.percona.com/doc/percona-monitoring-and-management/architecture.html 报警机制https://www.p ...
- MySQL出现:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms ago.
1.首先检查生产环境的机器是否ping的通和telnet的通数据库 2.排查数据库连接的参数 3.看数据量是否很大 参考: http://blog.csdn.net/sclxf/article/det ...
- ZooKeeper实现配置中心的实例(原生API实现)(转)
说明:要实现配置中心的例子,可以选择的SDK有很多,原生自带的SDK也是不错的选择.比如使用I0Itec,Spring Boot集成等. 大型应用通常会按业务拆分成一个个业务子系统,这些大大小小的子应 ...
- Maven使用GitHub项目目录搭建远程仓库
使用GtiHub的项目目录搭建第三方远程仓库,能免除使用服务器搭建Nexus私服,而且空间也是免费的.但是这种方式只适合小规模发布,毕竟搜索和版本控制是一个问题,如果需要更复杂的功能就只能转向Nexu ...
- 又通过一道题目,替换字符串 —— 剑指Offer
https://www.nowcoder.net/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage= ...
- Manthan, Codefest 16 F
寻找树上最大权值和的两条不相交的路径. 树形DP题.挺难的,对于我…… 定义三个变量ma[MAXN], t[MAXN], sum[MAXN] 其中,ma[i]代表i子树中,最长的路径和 t[i]代表i ...
- 畅谈HTML开发
现在,打开浏览器,各种各样的页面可以让人眼花缭乱,对于行外人看到的是美观效果是用户体验,对行内人很多其它的是关注技术和创造力. 对于开发者都知道DIV是一对html经常使用标签,DIV+CSS是一对非 ...
- iOS中的枚举:enum, NS_ENUM, NS_OPTIONS的使用区别
1.enum可以声明一般类型和位掩码(bitmasked)类型 例如: enum Test{// 一般枚举 TestA, TestB, TestC, }; enum{// 匿名枚举 TestA, Te ...