c#中 uint–byte[]–char[]–string相互轉換

來源:互聯網
上載者:User

uint-----byte[]-----char[]-----string

        在做一些互操作的時候往往需要一些類型的相互轉換,比如用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;    

    注意在跟api用uint進行字元互動的時候,一定要注意字元順序,涉及到api中高低位元據的問題,即擷取到api中DOWRD的資料在c#表示中往往是反序,所以在c#中擷取或者傳遞字串時一定要注意反序處理後才能轉換成uint給api使用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.