(C#基础) byte[] 之初始化, 赋值,转换。(转)
byte[] 之初始化赋值
用for loop 赋值当然是最基本的方法,不过在C#里面还有其他的便捷方法。
1. 创建一个长度为10的byte数组,并且其中每个byte的值为0.
byte[] myByteArray = new byte[10];
C# 在创建数值型(int, byte)数组时,会自动的把数组中的每个元素赋值为0. (注:如果是string[], 则每个元素为的值为null.
2. 创建一个长度为10的byte数组,并且其中每个byte的值为0x08.
byte[] myByteArray = Enumerable.Repeat((byte)0x08, 10).ToArray();
用linq来赋值,语句只要一条, 当然我们还可以赋值不同的,但是有一定规律的值。
byte[] res= Enumerable.Range(1, 1000).Select(c=>Convert.ToByte(c)).ToArray();
3. 直接赋值
byte[] myByteArray = new byte[] { 0x01, 0x02, 0x03 };
byte[] ---> ushort
byte[] array = new byte[] { 0xFE, 0x00 }; ushort register = BitConverter.ToUInt16(array, 0);
上述转换后register 的值为 0x00FE
byte[] array = new byte[] { 0x02, 0x01 ,0x04, 0x03 }; ushort register = BitConverter.ToUInt16(array, 0);
上述转化后,其实只是取了array[0], array[1].的值,最后register 的值是 0x00010002, 即258
byte[] -> string
public static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-","");
}
ushort ---> byte[]
ushort register = 0x00F0; byte[] arr = BitConverter.GetBytes(register);
在PC系统里, arr[0] = 0xF0(地位), arr[1] = 0x00 .
互换ushort中的两个字节

ushort number = 0x00F0; byte[] temp = BitConverter.GetBytes(number);
Array.Reverse(temp); ushort a = BitConverter.ToUInt16(temp, 0); ushort b = (ushort)(number << 8 | ((number & 0xFF00) >> 8));

byte[] => Struct

public StructType ConverBytesToStructure<StructType>(byte[] bytesBuffer)
{
// 检查长度。
if (bytesBuffer.Length != Marshal.SizeOf(typeof(StructType)))
{
throw new ArgumentException("bytesBuffer参数和structObject参数字节长度不一致。");
} IntPtr bufferHandler = Marshal.AllocHGlobal(bytesBuffer.Length);
for (int index = 0; index < bytesBuffer.Length; index++)
{
Marshal.WriteByte(bufferHandler, index, bytesBuffer[index]);
}
StructType structObject = (StructType)Marshal.PtrToStructure(bufferHandler, typeof(StructType));
Marshal.FreeHGlobal(bufferHandler);
return structObject;
}


代码 /// <summary>
/// 将byte[]还原为指定的struct,该函数的泛型仅用于自定义结构
/// startIndex:数组中 Copy 开始位置的从零开始的索引。
/// length:要复制的数组元素的数目。
/// </summary>
public static T BytesToStruct<T>(byte[] bytes, int startIndex, int length)
{
if (bytes == null) return default(T);
if (bytes.Length <= 0) return default(T);
IntPtr buffer = Marshal.AllocHGlobal(length);
try//struct_bytes转换
{
Marshal.Copy(bytes, startIndex, buffer, length);
return (T)Marshal.PtrToStructure(buffer, typeof(T));
}
catch(Exception ex)
{
throw new Exception("Error in BytesToStruct ! " + ex.Message);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}

Struct => byte[]

代码 /// <summary>
/// 将struct类型转换为byte[]
/// </summary>
public static byte[] StructToBytes(object structObj, int size)
{
IntPtr buffer = Marshal.AllocHGlobal(size);
try//struct_bytes转换
{
Marshal.StructureToPtr(structObj, buffer, false);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
catch (Exception ex)
{
throw new Exception("Error in StructToBytes ! " + ex.Message);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}

byte[] 数组比较

//You can use Enumerable.SequenceEqual method. using System;
using System.Linq;
...
var a1 = new int[] { 1, 2, 3};
var a2 = new int[] { 1, 2, 3};
var a3 = new int[] { 1, 2, 4};
var x = a1.SequenceEqual(a2); // true
var y = a1.SequenceEqual(a3); // false

参考: http://www.dotnetperls.com/initialize-array
转自:http://www.cnblogs.com/fdyang/archive/2013/10/20/3378974.html
(C#基础) byte[] 之初始化, 赋值,转换。(转)的更多相关文章
- (C#基础) byte[] 之初始化, 赋值,转换。
byte[] 之初始化赋值 用for loop 赋值当然是最基本的方法,不过在C#里面还有其他的便捷方法. 1. 创建一个长度为10的byte数组,并且其中每个byte的值为0. byte[] myB ...
- 关于C# byte[]与struct的转换
转自:http://blog.chinaunix.net/uid-215617-id-2213082.html Some of the C# code I've been writing recent ...
- 【C++自我精讲】基础系列五 隐式转换和显示转换
[C++自我精讲]基础系列五 隐式转换和显示转换 0 前言 1)C++的类型转换分为两种,一种为隐式转换,另一种为显式转换. 2)C++中应该尽量不要使用转换,尽量使用显式转换来代替隐式转换. 1 隐 ...
- C# Byte[] 转String 无损转换
C# Byte[] 转String 无损转换 转载请注明出处 http://www.cnblogs.com/Huerye/ /// <summary> /// string 转成byte[ ...
- OpenCV中IplImage图像格式与BYTE图像数据的转换
最近在将Karlsruhe Institute of Technology的Andreas Geiger发表在ACCV2010上的Efficent Large-Scale Stereo Matchin ...
- devexpress中ASPxGridView控件初始化赋值
写在ASPxGridView中OnCellEditorInitialize="ASPxGridView_progoods_CellEditorInitialize" 事件中: / ...
- byte与sbyte的转换
C#实现byte与sbyte的转换 byte[] mByte; sbyte[] mSByte = new sbyte[mByte.Length]; ; i < mByte.Length; i++ ...
- Java - byte[] 和 String互相转换
通过用例学习Java中的byte数组和String互相转换,这种转换可能在很多情况需要,比如IO操作,生成加密hash码等等. 除非觉得必要,否则不要将它们互相转换,他们分别代表了不同的数据,专门服务 ...
- 通过本质看现象:关于Integer受内部初始化赋值范围限制而出现的有趣现象
左手代码,右手文章.——朱季谦 这是我的第一篇技术博客,作为一名技术小菜鸟,总体而言显得很拙见,但也算是成长路上的一个小脚印,希望能在以后的日子里,可以对JAVA技术有一个更加深入的思考与认识. 前几 ...
随机推荐
- ACM/ICPC 之 用双向链表 or 模拟栈 解“栈混洗”问题-火车调度(TSH OJ - Train)
本篇用双向链表和模拟栈混洗过程两种解答方式具体解答“栈混洗”的应用问题 有关栈混洗的定义和解释在此篇:手记-栈与队列相关 列车调度(Train) 描述 某列车调度站的铁道联接结构如Figure 1所示 ...
- ACM/ICPC 之 数据结构-线段树思想(POJ2182,含O(n^2)插入式解法)
这道题在一定程度上体现了线段树的一种用法,解决的问题是:对于总计n个元素的第i个元素,已知其在[1,i]上部分序列的排名,求第i个元素在所有n个元素中的排名. 当然这道题数据比较水,所以用O(n^2) ...
- C#传真传址 结构体
1.传真 传址 namespace 传值_传址 { class Program { //格式1:无参无返 public void LeiJia() { Console.Write("请输入 ...
- Android实现Banner界面广告图片循环轮播(包括实现手动滑动循环)
前言:经常会看到有一些app的banner界面可以实现循环播放多个广告图片和手动滑动循环.本以为单纯的ViewPager就可以实现这些功能.但是蛋疼的事情来了,ViewPager并不支持循环翻页.所以 ...
- 【leetcode】Rotate List(middle)
Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1 ...
- 【linux】find删除指定时间之前的文件
今天磁盘满了,想删掉一些老的日志文件.开始想写个python脚本,转念一想,可能shell脚本好点.结果发现,根本不用写脚本,一个find指令就可以解决问题了. 先上指令 -exec rm {} \; ...
- iOS - iPhone开发 UILocalNotification的使用
OS下的Notification的使用 Notification 是智能手机应用编程中非常常用的一种传递信息的机制,而且可以非常好的节省资源,不用消耗资源来不停地检查信息状态(Pooling),在iO ...
- VS2013调试时,IIS Express Worker Process 已停止工作
之前调试都没有报错的,今天突然报错了,然后网上找了下资料,很快解决了问题 这是我报错的提示 解决办法: 用管理员身份运行CMD,输入netsh winsock reset并回车(注意,必须是已管理员身 ...
- 基于SSH2的OA项目1.1_20161207_业务开发
1.1建立用户的pojo模型 建立user.java package org.guangsoft.pojo; import java.util.HashSet; import java.util.Se ...
- July 4th, Week 28th Monday, 2016
Goals determine what you are going to be. 你的目标决定你将成为怎样的人. What are your goals? What kind of people y ...