C# 转换uint,byte[],char[],string, short[]<->byte[] 结构体和字节数组转化

来源:互联网 发布:软件可靠性分配付 编辑:程序博客网 时间:2024/04/29 23:18
在在做一些互操作的时候往往需要一些类型的相互转换,比如用c#访问win32api的时候往往需要向api中传入DWORD参数 即:uint参数这些数值所表示的数据在实际的应用中可能需要以字符的形式显示,但是c#对api的关系无法跟c++相比,所以在c#中进行一些类型数据的转换十分必要了,
    下面将用到的一些简单的转换操作贴上来,方便记忆 
     

uint--->byte[]

       byte[] bpara  =System.BitConverter.GetBytes(uint upara);

 

byte[]--->uint

       uint upara= System.BitConverter.ToUint32(bpara);

 

byte--->char

       system.convert.tochar(bpara);

 

char--->byte

       system.convert.tobyte(cpara);

 

byte[]--->char[]

      (1)char[] cpara= System.Text.Encoding.Default.GetChars(bpara);(1)

(2)char[] cpara=new char[bpara.length];

for(int i=0;i <bpara.length;i ++){char[i]=system.convert.tochar(bpara[i]);}   

      (3)char[] cpara= new ASCIIEncoding().GetChars(bpara);

 

char[]--->byte[]

      (1)byte[] bpara= System.Text.Encoding.Default.GetBytes(cpara);    

      (2) byte[] bpara=   new ASCIIEncoding().GetBytes(cpara);

char[]--->string

      String spara=new String(cpara);

 

string---char[]

     char[] cpara=spara.ToCharArray()

   

uint---->char[]

      (1)uint-->byte[];

      (2)byte[]-->char[];   

            

uint--->string

     (1)uint-->byte[];

     (2)byte[]-->char[];

     (3)char[]-->string;

 

byte[]--->string

    (1).byte[]-->char[];

    (2).char[]-->string;

   (3) new ASCIIEncoding().GetString(bprar);

char[]--->uint

   (1).char[]-->byte[];

   (2).byte[]-->uint;

string--->byte[]

    bpara= System.Text.Encoding.Default.GetBytes(sPara)

 

string--->uint

     (1)string-->byte[];

     (2)byte[]-->uint;

C#中short数组的文件读写方法

private void button1_Click(object sender, EventArgs e)
{
    short[] buffer = new short[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    FileStream vFileStream = new FileStream(@"c:\temp\temp.dat",
        FileMode.Create, FileAccess.Write);
    byte[] temp = new byte[buffer.Length * sizeof(short)];
    Buffer.BlockCopy(buffer, 0, temp, 0, temp.Length);
    vFileStream.Write(temp, 0, temp.Length);
    vFileStream.Close();
}
 
protected void button2_Click(object sender, EventArgs e)
{
    FileStream vFileStream = new FileStream(@"c:\temp\temp.dat",
        FileMode.Open, FileAccess.Read);
    byte[] temp = new byte[vFileStream.Length];
    vFileStream.Read(temp, 0, temp.Length);
    short[] buffer = new short[temp.Length / sizeof(short)];
    Buffer.BlockCopy(temp, 0, buffer, 0, buffer.Length * sizeof(short));
    vFileStream.Close();
    Text = string.Format("{0},{1},{2}", buffer[0], buffer[1], buffer[2]);
}

    注意在跟api用uint进行字符交互的时候,一定要注意字符顺序,涉及到api中高低位数据的问题,即获取到api中DOWRD的数据在c#表示中往往是反序,所以在c#中获取或者传递字符串时一定要注意反序处理后才能转换成uint给api使用,有机会好好总结一下贴上来。    

 

c#中关于结构体和字节数组转化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespaceFileSendClient
{
  
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    structStructDemo
    {
         
        publicbyte a;
        publicbyte c;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
        publicbyte[] b;
        publicbyte d;
        publicint e;
         
    }
    unsafeclass Program
    {
        staticvoid Main(string[] args)
        {
            StructDemo sd;
            sd.a = 0;
            sd.d = 0;
            sd.c = 0;
            sd.b =new byte[3] { 0, 0, 1 };
            sd.e = 5;
            intsize = 0;
            //此处使用非安全代码来获取到StructDemo的值
            unsafe
            {
                size = Marshal.SizeOf(sd);
            }
              
            byte[] b = StructToBytes(sd,size);
  
            ByteToStruct(b,typeof(StructDemo));
  
        }
  
  
        //将Byte转换为结构体类型
        publicstatic byte[] StructToBytes(objectstructObj,intsize)
        {
            StructDemo sd;
            intnum = 2;
            byte[] bytes =new byte[size];
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体拷到分配好的内存空间
            Marshal.StructureToPtr(structObj, structPtr,false);
            //从内存空间拷贝到byte 数组
            Marshal.Copy(structPtr, bytes, 0, size);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            returnbytes;
  
        }
  
        //将Byte转换为结构体类型
        publicstatic objectByteToStruct(byte[] bytes, Type type)
        {
            intsize = Marshal.SizeOf(type);
            if(size > bytes.Length)
            {
                returnnull;
            }
            //分配结构体内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷贝到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            objectobj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            returnobj;
        }
    }
}

0 0