C# byte[]数组,问答
2013-03-07 20:42
232 查看
比如 byte[] cmdData = {85,85,83,83,255,123,99,33,55,1,1}
长度为 11
用什么方法可以 从 第4位开始截取 5 个
即:255,123,99,33,55
答:
byte[] cmdData = { 85, 85, 83, 83, 255, 123, 99, 33, 55, 1, 1 };
byte[] newData = new byte[5];
Array.Copy(cmdData, 4, newData,0, 5);
--------------------------------------------------------------------------------------
问:
比如有:
byte[] a = {0x01,0x02,0x03};
byte[] b = {0x04,0x05,0x06};
byte[] c;
有没有比较简单的方法来连接a 和 b 两个数组到c里去?而不用循环来写进去?
答:
byte[] c = new byte[a.Length + b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
--------------------------------------------------------------------------------------
问:
怎样把Object对象转换成字节数组?
请问怎样把Object对象转换成字节数组,用来在网络上传输?非常感谢!!!!
答:
----------------------
问如何将对象的实体转换为byte[]?
[Serializable]
public class student
{
public string name;
public int age;
}
private void Form1_Load(object sender, EventArgs e)
{
student student1 = new student();
student1.name = "zhangsan";
student1.age = 10;
byte[] tBytes = null;
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, student1);
tBytes = memoryStream.ToArray();
}
-------------------------
2序列化和反序列化
首先这个类必须是可序列化的,例如DataTable,又或者下面这样:
[Serializable]
public class GradResume
{
/// <summary>
/// 用户ID。
/// </summary>
public string UserID;
/// <summary>
/// 登录名。
/// </summary>
public string UserName;
.......................
序列化和反序列化的代码如下:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
//新建类GradResume的实例
GradResume aaa = new GradResume();
aaa.UserID = "123";
aaa.UserName = "eddiezhong";
//序列化对象
BinaryFormatter binaryFormatter = new BinaryFormatter();
System.IO.MemoryStream mStm1 = new System.IO.MemoryStream();
binaryFormatter.Serialize(mStm1,aaa);
byte[] tmpBytes = mStm1.ToArray();
mStm1.Close();
//tmpBytes就可以用来保存数据库了或者写文件
//读数据库或者文件文件重新获得tmpBytes
//反序列化二进制数组
System.IO.MemoryStream mStm2 = new System.IO.MemoryStream(tmpBytes);
mStm2.Position = 0;
object newObj = binaryFormatter.Deserialize(mStm2);
mStm2.Close();
//得到GradResume对象
GradResume bbb = (GradResume)newObj;
this.TextBox1.Text = bbb.UserID;
this.TextBox2.Text = bbb.UserName;
相关文章推荐
- c#中文字符串与byte数组互相转化
- 【C# 基础】ArrayList 转换成byte数组
- C#中 Unicode 字符串转换 iso8859-15 byte数组
- C#通信,结构体和byte数组互转
- C#下byte数组与string的相互转换
- C#中结构体和byte数组的转化
- c# 将byte数组保存成图片
- c# string 转byte[]数组转换
- c# 合并byte数组
- C# byte数组常用扩展浅析
- 请教一个C#中将byte[]数组转换为Image的问题
- C# 保存 byte 数组 到文件中, 用vs2005 打开该文件查看
- C# byte数组转long型数据
- [C#]image与byte数组的转换
- C# 常见的字节数组 byte[] 复制方法
- C#对byte数组压缩和解压
- c++与C# winform的消息通讯--(结构体与byte数组的使用)
- C# byte数组常用扩展浅析
- C# 中字符串string和字节数组byte[]之间的转换
- [c#]string和byte 数组转换的快速方法(采用unsafe)