大米CMS官网论坛,大米站长联盟,大米站长之家,大米开发者社区

标题: c二进制与16进制互相转换 [打印本页]

作者: 追影    时间: 2018-10-11 09:33
标题: c二进制与16进制互相转换
  1. void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)

  2. {
  3.         short i;
  4.         unsigned char highByte, lowByte;


  5.         for (i = 0; i < sourceLen; i++)
  6.         {
  7.                 highByte = source[i] >> 4;
  8.                 lowByte = source[i] & 0x0f;


  9.                 highByte += 0x30;


  10.                 if (highByte > 0x39)
  11.                         dest[i * 2] = highByte + 0x07;
  12.                 else
  13.                         dest[i * 2] = highByte;


  14.                 lowByte += 0x30;
  15.                 if (lowByte > 0x39)
  16.                         dest[i * 2 + 1] = lowByte + 0x07;
  17.                 else
  18.                         dest[i * 2 + 1] = lowByte;
  19.         }
  20.         return;
  21. }


  22. //字节流转换为十六进制字符串的另一种实现方式

  23. void Hex2Str(const char *sSrc, char *sDest, int nSrcLen)
  24. {
  25.         int  i;
  26.         char szTmp[3];


  27.         for (i = 0; i < nSrcLen; i++)
  28.         {
  29.                 sprintf(szTmp, "%02X", (unsigned char)sSrc[i]);
  30.                 memcpy(&sDest[i * 2], szTmp, 2);
  31.         }
  32.         return;
  33. }



  34. //十六进制字符串转换为字节流
  35. void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)
  36. {
  37.         short i;
  38.         unsigned char highByte, lowByte;

  39.         for (i = 0; i < sourceLen; i += 2)
  40.         {
  41.                 highByte = toupper(source[i]);
  42.                 lowByte = toupper(source[i + 1]);


  43.                 if (highByte > 0x39)
  44.                         highByte -= 0x37;
  45.                 else
  46.                         highByte -= 0x30;


  47.                 if (lowByte > 0x39)
  48.                         lowByte -= 0x37;
  49.                 else
  50.                         lowByte -= 0x30;


  51.                 dest[i / 2] = (highByte << 4) | lowByte;
  52.         }
  53.         return;
  54. }
复制代码







欢迎光临 大米CMS官网论坛,大米站长联盟,大米站长之家,大米开发者社区 (https://www.damicms.com/bbs/) Powered by Discuz! X3.1