(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技术有一个更加深入的思考与认识. 前几 ...
随机推荐
- STL---list(列表)
Lists将元素按顺序储存在链表中. 与 向量(vectors)相比, 它允许快速的插入和删除,但是随机访问却比较慢. list的类模板声明为 template<class T, class A ...
- 流程图制作在云上 https://www.processon.com/
流程图制作在云上 : https://www.processon.com/
- Linux设置交换分区swap
参考: http://www.vpser.net/opt/vps-add-swap.html https://www.zntec.cn/archives/vps-swap.html http://yz ...
- 基础01 dos命令
常见的dos命令: 盘符: 进入指定的盘下面. 操作文件夹: dir 列出当前控制 ...
- MySQL字符集转换引发插入乱码问题
根据http://www.cnblogs.com/cchust/p/4601536.html进行验证测试 问题背景 在mysql上面执行一条普通的insert语句,结果报错: Incorrect st ...
- Visual Studio 2013 (vs2013)中“向前定位”,“向后定位”按钮
Visual Studio 2013 (vs2013)中默认的界面中似乎没有向前向后定位这个非常实用的功能,下面是把它们找出来的方法: 方法1:右键-->工具栏空白处-->最下面,自定义- ...
- ffmpeg-20160806-bin.7z
ESC 退出 0 进度条开关 1 屏幕原始大小 2 屏幕1/2大小 3 屏幕1/3大小 4 屏幕1/4大小 S 下一帧 [ -2秒 ] +2秒 ; -1秒 ' +1秒 下一个帧 -> -5秒 f ...
- CentOS新系统必做的几件事
一.修改yum源 要知道国外的yum源是很慢的,为了提高效率,更变为网易yum源. 首先备份/etc/yum.repos.d/CentOS-Base.repo(系统默认源): mv /etc/yum. ...
- Effective C++ -----条款10: 令operator=返回一个reference to *this
比如: Widget& operator=(const Widget& rhs) { ... return* this; } 令赋值(assignment)操作符返回一个referen ...
- win7 ubuntu10.04双系统,重装win7后,修复双启动项
进入ubuntu的liveCD(即在试用ubuntu里),在终端里操作 首先要找到自己的ubuntu系统挂载在那个sda下面.可以用sudo fdisk -l 这个命令.然后: 1. sudo -i ...