首页 > 编程语言 > 详细

C++字符串16进制转换

时间:2015-10-30 12:50:05      阅读:248      评论:0      收藏:0      [点我收藏+]

这段时间在做一个图片传输的功能,因为图片不是很大而且传输频率也不是非常的频繁,于是就做的是一次传输。先把图片读入内存,然后再转为16进制,然后发送。

std::string ReadFiletoHex(std::string path)
{
   unsigned char c;
   char buf[2];
   std::string result = "";
   std::ifstream fread(path,std::ios::binary);
   while(fread.read((char*)(&c), sizeof(c)))
   {
      sprintf(buf, "%02X", c);
      result += buf;
   }
   fread.close();

   return result;
}

int WriteHextoFile(std::string file,std::string path)
{
   std::string hex = file;
   int len = hex.length();
   std::string newString;
   for(int i=0; i< len; i+=2)
   {
      std::string byte = hex.substr(i,2);
      char chr = (char) (int)strtol(byte.c_str(), NULL, 16);
      newString.push_back(chr);
   }

   std::ofstream fwrite;
   fwrite.open(path, std::ofstream::out |std::ios::binary);
   fwrite.write(newString.c_str(), sizeof(char) * (newString.size()));
   fwrite.close();
   return 0;
}


C++字符串16进制转换

原文:http://my.oschina.net/bobwei/blog/523873

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!