C++ - Encoding data to hex and back

29. March 2012 20:29

 

Sometime it can be a problem when working with network protocols or any sort of client / server communications that use text based protocol it can be a problem to transmit certain types of data which contain quotes or other types of charaters. It also has a simalar problem for storing data in ini files.

 

There is quite a simple solution to this. Encode the data some how to send the data encoded and decode it at the other end. It would probably be better to use the well known base64 encoding but if you don't have an implementation of it avilable the following can work just as well.

 

The encoder

 

std::string HexEncode(std::string str) {
	std::string tmp;
	const char *c = str.c_str();
	char buf[3];
	
	while(*c != 0) {
		sprintf(buf, "%02X", (unsigned char) *c);
		tmp += buf;
		c++;
	}

	return tmp;
}

 

 

The decoder

 

 

std::string HexDecode(std::string str) {
	std::string tmp;
	const char *c = str.c_str();
	unsigned int x;
	
	while(*c != 0) {
		sscanf(c, "%2X", &x);
		tmp += x;
		c += 2;
	}
	
	return tmp;
}

 

The only problem with the above is that it does double the size of the data once it is encoded but since most other encoding like base64 or uuencoding.

E-mail Kick it! DZone it! del.icio.us Permalink