Skip to main content
GameDev.net gamedev.net
🔒 Locked

Hex to string, kinda?

Started by Eponick Nov 17, 2004 at 2:48 PM 4 replies 900+ views
Original Post
Eponick
Eponick
I was wondering if theres a function or something to convert hex to a string, kinda. Example: I want to convert 0x82 ('\x82') to "82", or 0xE2 to "E2", etc.
Lead ProgrammerDawn of Daria
snk_kid
snk_kid
what programming language are you using.
Eponick
Eponick
Erm, yeah. Sorry I forgot to mention it.
C++, MSVC 6.0 is the compiler/IDE if needed
Lead ProgrammerDawn of Daria
snk_kid
snk_kid
here is one way (not the only way), try this:

#include <string>#include <sstream>#include <iomanip>#include <iostream>int main() {   int foo = 0xE2;   std::ostringstream oss;   oss << std::setbase(16) << foo;   std::string s = oss.str();   std::cout << s << std::endl;}
Endogenous
Endogenous
int x = 0x0F;char buffer[30];snprintf(buffer,30,"%.2x",x);


Would probably also do the trick, if you feel like using string.h.
Aprosenf
Aprosenf
char hexDigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; std::string HexCharToString(unsigned char x){	std::string result(2); 	result[0] = hexDigits[x >> 4]; // Upper 4 bits	result[1] = hexDigits[x & 0x0F]; // Lower 4 bits; 	return result;}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.