zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    第十五章:Spring Boot 与 开发热部署
    第一章:(1)分布式基础理论
    第一章:(4)Dubbo 案例 HelloWorld
    第一章:(2)Dubbo核心概念
    第十四章:(3)Spring Boot 与 分布式 之 SpringCloud
    web安全测试AppScan扫描工具
    Cheatsheet: 2013 02.01 ~ 02.15
    Cheatsheet: 2013 04.17 ~ 04.30
    Cheatsheet: 2013 02.16 ~ 02.28
    Cheatsheet: 2013 01.21 ~ 01.31
  • 原文地址:https://www.cnblogs.com/gzoof/p/9993405.html
Copyright © 2011-2022 走看看