在C#语言中十六进制字符串与字节型数组的相互转换

11 篇文章 0 订阅
5 篇文章 0 订阅

border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_336_280.htm" frameborder="0" width="340" scrolling="no" height="282">

由于用到了十六进制字符串与字节型数组的相互转换,前一段时间从网上看到了一个串口类中有这么一个转换函数,但是在调试过程中出现错误,经过测试最终修改为以下:

 class HexCon
 {
  // 把字节型转换成十六进制字符串,最终不带有“0x”标志。

  public static string ByteToString(byte[] InBytes)
  {
   string StringOut="";
   foreach (byte InByte in InBytes)
   {
    StringOut=StringOut + String.Format("{0:X2}",InByte) + " ";
   }
   
   return StringOut.Trim();
  }

//把十六进制字符串转换成字节型。

border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_468_60.htm" frameborder="0" width="470" scrolling="no" height="62">

  public static byte[] StringToByte(string InString)
  {
   string[] ByteStrings;
   int      TmpIndex;
   ByteStrings = InString.Split(" ".ToCharArray());
   byte[] ByteOut;
   ByteOut = new byte[ByteStrings.Length];
   for (int i = 0;i<=ByteStrings.Length-1;i++)
   {
    TmpIndex = ByteStrings[i].ToLower().IndexOf("0x");
    if (TmpIndex >= 0)
    {
     ByteOut[i] = byte.Parse(ByteStrings[i].Remove(TmpIndex,2),System.Globalization.NumberStyles.HexNumber);
    }
    else
    {
     ByteOut[i] = byte.Parse(ByteStrings[i],System.Globalization.NumberStyles.HexNumber);
    }
   } 
   return ByteOut;
  }
 }

border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_468_60.htm" frameborder="0" width="470" scrolling="no" height="62">

border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_ads_468_15.htm" frameborder="0" width="470" scrolling="no" height="18">

border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_syndication_468_60.htm" frameborder="0" width="470" scrolling="no" height="62">

搜索其它相关资源,请用Google搜索:
border="0" name="I1" align="middle" marginwidth="1" marginheight="1" src="http://www.b199.cn/blog_ads/Google_search_40.htm" frameborder="0" width="460" scrolling="no" height="40">

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Everest

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值