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

在在做一些互操作的时候往往需要一些类型的相互转换,比如用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使用,有机会好好总结一下贴上来。    

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace FileSendClient
{
  
     [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
     struct StructDemo
     {
         
         public byte a;
         public byte c;
         [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
         public byte [] b;
         public byte d;
         public int e;
         
     }
     unsafe class Program
     {
         static void 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;
             int size = 0;
             //此处使用非安全代码来获取到StructDemo的值
             unsafe
             {
                 size = Marshal.SizeOf(sd);
             }
              
             byte [] b = StructToBytes(sd,size);
  
             ByteToStruct(b, typeof (StructDemo));
  
         }
  
  
         //将Byte转换为结构体类型
         public static byte [] StructToBytes( object structObj, int size)
         {
             StructDemo sd;
             int num = 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);
             return bytes;
  
         }
  
         //将Byte转换为结构体类型
         public static object ByteToStruct( byte [] bytes, Type type)
         {
             int size = Marshal.SizeOf(type);
             if (size > bytes.Length)
             {
                 return null ;
             }
             //分配结构体内存空间
             IntPtr structPtr = Marshal.AllocHGlobal(size);
             //将byte数组拷贝到分配好的内存空间
             Marshal.Copy(bytes, 0, structPtr, size);
             //将内存空间转换为目标结构体
             object obj = Marshal.PtrToStructure(structPtr, type);
             //释放内存空间
             Marshal.FreeHGlobal(structPtr);
             return obj;
         }
     }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值