• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Psychopathetica

Hexadecimals

19 posts in this topic

This may sound strange but I know how to display hexadecimals in C with the printf() using \x and in C++ using cout << hex << your_int_here, but what if I wanted to store that hexadecimal in a string? And I'm not talking about using the char data type but rather the string data type from the library #include <string>. Is it possible without having to design my own hex to string conversion function?

0

Share this post


Link to post
Share on other sites

But the thing is that all those methods still involve the console window. If you were wanting to save it to file, or a listbox, label, or messagebox, couldn't you use sprintf() to put the result in a string and display it using any of those?

 

[EDIT]

Seems like Im right:

#include <windows.h>
#include <string>
using namespace std;

int main()
{
	int number = 11;
	string Text[255];
	sprintf((char *)Text, "The hexadecimal value of number is: %x", number);
	MessageBox(NULL, (char *)Text, "typedef", MB_OK);

	return 0;
}

And although it works on VS 2012, I tried it on VS 2013, and I got a warning saying it might be unsafe, use sprintf_s instead. Very strange. And even then the console window crashes afterwards no matter which sprintf I use.

 

As an experiment I even tried not using a Messagebox, and displayed it in the console window. It works until I close the console window, then crashes. Its only if I comment out the sprintf_s that it doesnt crash:

#include <windows.h>
#include <string>
#include <iostream>
using namespace std;

int main()
{
	int number = 11;
	string Text[255];
	sprintf_s((char *)Text, sizeof(Text),"The hexadecimal value of number is: %x", number);
	//MessageBox(NULL, (char *)Text, "typedef", MB_OK);
	cout << (char *)Text << endl;
	system("pause");
	return 0;
}
Edited by Psychopathetica
-6

Share this post


Link to post
Share on other sites
Psychopathetica, it crash because Text is an array of std::string when it should have been an array of char.
0

Share this post


Link to post
Share on other sites

Setting char *Text instead of string Text[255] still crashes the console window. But this works at least:

#include <windows.h>
#include <string>
#include <iostream>
using namespace std;

int main()
{
	int number = 11;
	char Text[255];
	sprintf_s(Text, sizeof(Text), "The hexadecimal value of number is: %x", number);
	MessageBox(NULL, Text, "typedef", MB_OK);
	cout << (char *)Text << endl;
	system("pause");
	return 0;
}

However I still wanna be able to store the data in a string rather than a char.

Edited by Psychopathetica
0

Share this post


Link to post
Share on other sites
Why not just convert to base 16 (hex) by yourself? The math is not that hard (num % 16, num /= 16).
See here.
0

Share this post


Link to post
Share on other sites

Here's some completely untested code that should do the trick. It should be equivalent to the much simpler sprintf(result, "%08x", value);
 
I don't think it's especially tricky to write. It's not so easy to read and understand though.

[spoiler] 

// Assumes result has at least 9 bytes of space to write to
void GetHexString(uint32_t value, char *result)
{
  static const char *digits = "0123456789ABCDEF";
  uint32_t shift = 32-4;
  for (int i=0; i < 8; i++)
  {
    result[i] = digits[(value >> shift) & 0xf];
    shift -= 4;
  }
  result[8] = 0;
}

[/spoiler]

1

Share this post


Link to post
Share on other sites
That code does look pretty good. It's not exactly equivalent to the sprintf call, because you are using capital letters.
0

Share this post


Link to post
Share on other sites
This is the function I use:
std::string UnsignedIntToHexString(uint32_t value, const std::string &prefix = "0x", size_t digits = 8, bool uppercase = true)
{
	return UnsignedIntToHexString((uint64_t)value, prefix, digits, uppercase);
}

//Converts an integer to a std::string, in hexadecimal format. 'digits' is the fixed number of digits that show up.
//For example, 0x00FF00AA shows zeroes if 'digits' is 8, and only shows 0x00AA, if 'digits' is 4.
std::string UnsignedIntToHexString(uint64_t value, const std::string &prefix = "0x", size_t digits = 16, bool uppercase = true)
{
	const char *symbols = (uppercase? "0123456789ABCDEF":"0123456789abcdef");

	//Fill everything with zeroes (including the digits above the first 8 digits).
	std::string result((prefix.size() + digits), '0');

	//I'm kinda cheating here. If we have less than 8 digits, we intentionally are subtracting
	//from 'startIndex'. For example, if we have 6 digits, we subtract 2 from the starting index,
	//because 'case 6' in the switch statement lower down this function adds 2 to the index.
	const size_t startIndex = prefix.size() + (int(digits) - 16);
	digits %= 16; //This is a 64 bit number, so any digit above 16 leave as zero.

	//Write the prefix, if there is one.
	if(!prefix.empty())
	{
		result.replace(0, prefix.size(), prefix);
	}

	/*
		Each 'digit' of a hexadecimal number is 4 bits (2^4 = 16).

		First, shift the 4 bits we want over to the far-right side of the number.
		(value >> 28)

		Second, mask the value, so it's *only* those 4 bits (a value between 0 and 15)
		((...) & 0x0F)

		Finally, use that value to lookup the symbol in the symbol array.
		symbols[ ... ]
	*/
	switch(digits)
	{
		//I am intentionally using case-statement fall-through here.
		case 16: result[startIndex + 0] = symbols[((value >> 60) & 0x0F)];
		case 15: result[startIndex + 1] = symbols[((value >> 56) & 0x0F)];
		case 14: result[startIndex + 2] = symbols[((value >> 52) & 0x0F)];
		case 13: result[startIndex + 3] = symbols[((value >> 48) & 0x0F)];
		case 12: result[startIndex + 4] = symbols[((value >> 44) & 0x0F)];
		case 11: result[startIndex + 5] = symbols[((value >> 40)  & 0x0F)];
		case 10: result[startIndex + 6] = symbols[((value >> 36)  & 0x0F)];
		case 9: result[startIndex +  7] = symbols[((value >> 32)  & 0x0F)];
		case 8: result[startIndex +  8] = symbols[((value >> 28) & 0x0F)];
		case 7: result[startIndex +  9] = symbols[((value >> 24) & 0x0F)];
		case 6: result[startIndex + 10] = symbols[((value >> 20) & 0x0F)];
		case 5: result[startIndex + 11] = symbols[((value >> 16) & 0x0F)];
		case 4: result[startIndex + 12] = symbols[((value >> 12) & 0x0F)];
		case 3: result[startIndex + 13] = symbols[((value >> 8)  & 0x0F)];
		case 2: result[startIndex + 14] = symbols[((value >> 4)  & 0x0F)];
		case 1: result[startIndex + 15] = symbols[((value >> 0)  & 0x0F)];
		default: break;
	}

	return result;
}
And binary:
//Converts an integer to a std::string, in binary format. 'digits' is the fixed number of digits that show up.
//'blockSize' is the number of characters before being seperated by 'seperator' (usually a space or a hyphen).
std::string UnsignedIntToBinaryString(uint32_t value, size_t digits = 32, size_t blockSize = 0, char seperator = '-')
{
	return UnsignedIntToBinaryString((uint64_t)value, digits, blockSize, seperator);
}

std::string UnsignedIntToBinaryString(uint64_t value, size_t digits = 64, size_t blockSize = 0, char seperator = '-')
{
	//A blockSize of 0 means someone probably wanted a single block of every digit.
	if(blockSize == 0) blockSize = digits;
	if(digits == 0) digits = 64; //A 64 bit variable, to show it fully, requires 64 digits.

	//Figure out how many seperators we'll have.
	//We subtract one, if a seperator will land on the very end.
	size_t numSeperators = (digits / blockSize) - ((digits % blockSize) == 0? 1 : 0);

	//Allocate our entire string in advance.
	std::string result(digits + numSeperators, '#');

	size_t seperatorCountdown = blockSize;
	for(size_t i = result.size(); i--> 0; )
	{
		result[i] = ((value & 1) ? '1': '0');
		value >>= 1; //Shift the bits over one spot.

		//Add a seperator if our countdown reaches 0, unless we are at the end of the number.
		if(--seperatorCountdown == 0 && i != 0)
		{
			result[--i] = seperator;
			seperatorCountdown = blockSize;
		}
	}

	return result;
}
I *think* I wrote those functions myself (it's been awhile, and usually I add a comment with the source if it wasn't written by me), but I got the idea of the array of symbols + lookup index from someone else's code. I definitely wrote the binary one.

Note that the hexadecimal one doesn't loop, so it's (needlessly) lightning fast. Sometimes I optimize string formatting functions just for the heck of it, as code warm-ups when I'm procrastinating or just getting back into coding after a break. Edited by Servant of the Lord
0

Share this post


Link to post
Share on other sites

Can someone tell me why we aren't using the stringstream solution provided by frob again?

#include <iostream>
#include <sstream>

int main()
{
    int myNumber = 0xDEAD;
    
    // conversion to hex string
    std::stringstream ss; ss << std::hex << myNumber;
    std::string myHexString = ss.str();
    
    std::cout << myHexString << std::endl;
    return 0;
}

OP specifically requested:

 

[...] the string data type from the library #include <string>
Is it possible without having to design my own hex to string conversion function?

If you need upper case, you can add:

#include <algorithm>
std::transform( myHexString.begin(), myHexString.end(), myHexString.begin(), ::toupper );

And if you need the "0x" prefix you can do that in the string stream or insert it into the string after converting to upper case:

ss << "0x" << std::hex << myNumber; // either this
myHexString.insert( 0, "0x" ); // or this
Edited by TheComet
2

Share this post


Link to post
Share on other sites

Can someone tell me why we aren't using the stringstream solution provided by frob again?

 
Because, to do a simple thing, you have to write several lines of code.
void FuncWantingAString(std::string hexString);

int main()
{
   int value = 0xBEEF;
   
   //Single-func:
   FuncWantingAString(UnsignedIntToHexString(value));

   //String-stream:
   std::stringstream ss;
   ss << std::hex << myNumber;
   FuncWantingAString(ss.str());
}
One job (convert from int to string) should be one function call, IMO.
Stringstream is nice for formatting a larger text string with multiple values... but for a single conversion, a function is much nicer. C++11 added std::to_string(), but they probably should have allowed you to pass in a format as an optional parameter.
0

Share this post


Link to post
Share on other sites
Exactly. Alternatively:
//Converts an integer into a std::string, in the base 'base'.
std::string IntToStringBase(uint32_t value, Base base)
{
	std::stringstream stream;

	if(base == Base::Octal) stream.setf(std::ios_base::oct, std::ios_base::basefield);
	else if(base == Base::Hexadecimal) stream.setf(std::ios_base::hex, std::ios_base::basefield);
	else stream.setf(std::ios_base::dec, std::ios_base::basefield);

	stream << value;

	return stream.str();
}
0

Share this post


Link to post
Share on other sites

And if you need the "0x" prefix you can do that in the string stream or insert it into the string after converting to upper case:

ss << "0x" << std::hex << myNumber; // either this
myHexString.insert( 0, "0x" ); // or this

 

Or simply:

ss << std::showbase << std::hex << myNumber;

 

Which has the distinct advantage that you don't have to manually add the 0x to every single hex value.

1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0