C#字節取高低位以及byte和string的轉換


byte a = 0xF9;
string high = Convert.ToString((a & 0xf0) >> 4);// 這里的位操作數以及位移的數目可以根據自己的需要修改
string low = Convert.ToString(a & 0x0f);// 這里的位操作數以及位移的數目可以根據自己的需要修改

 byte和string的轉換

 private static byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

應用例子,對byte按位取反后得到byte

private byte GetOppData(byte bData) {

            string s = Convert.ToString(bData, 16);
            int d = Convert.ToUInt16(s, 16);
            d = ~d;
            string sdata = Convert.ToString(d, 16);
            Console.WriteLine(sdata);
            string realSData = sdata.Substring(6);
            Console.WriteLine(realSData);
            byte[] bHex=HexToByte(realSData);
            return bHex[0];
        }
 //string類型轉成byte[]: 

byte[] byteArray = System.Text.Encoding.Default.GetBytes ( str );
//byte[]轉成string:
string str = System.Text.Encoding.Default.GetString ( byteArray );
//其它編碼方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如:string類型轉成ASCII byte[]:("01" 轉成 byte[] = new byte[]{ 0x30, 0x31})
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str );

//ASCII byte[] 轉成string:(byte[] = new byte[]{ 0x30, 0x31} 轉成 "01")
string str = System.Text.Encoding.ASCII.GetString ( byteArray );

引用: https://bbs.csdn.net/topics/370198959


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM