这段时间在做一个图片传输的功能,因为图片不是很大而且传输频率也不是非常的频繁,于是就做的是一次传输。先把图片读入内存,然后再转为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; }
原文:http://my.oschina.net/bobwei/blog/523873