About the Blog

Back to Scriptionary

The Scriptionary blog is part of the Scriptionary wiki. Informal news and information will be announced here.

More…

Advertisement

Popular Tags

The tag with the most posts is the largest and vice versa.

Amount of Digits in an Integer

11 October 2008 - 16:59, By E. Luten

Here’s another little snippet that might come in handy in your programmatic travels. I’ll show you an example of usage below, which might also be of interest to you. The code presented is in C, not C++. First, the code to count the amount of digits in an integer:

const size_t intlen(long long int Num)
{
	size_t out = 1;
	while (Num /= 10) ++out;
	return out;
}; // numlen

Looks simple enough; simply count the amount of times we can divide the number by 10 without the result being zero. This function takes a copy of an int (or long long) so that we don’t have to copy the number inside the body of the function and returns a size_t (unsigned int).

As for the usage example, it’s a bit more complex and might seem a bit “obfuscated” at first, but fear not, I will explain below.

void inttoa(long long int Num, char** RetVal)
{
	size_t neg = (Num < 0);
	size_t len = intlen(Num) + (neg ? 1 : 0); // add one for the "-" character
	size_t i;

	*RetVal = (char *) malloc(sizeof(char) * (len + 1));

	if (NULL == (*RetVal))
		return; // bad malloc

	if (neg)
		Num = -Num; // make pos if neg

	for (i = len; i; (Num /= 10), --i) // loop backwards
		(*RetVal)[i-1] = (char)((Num % 10) + '0'); // add modulo to char zero

	if (neg)
		(*RetVal)[0] = '-'; // first char

	(*RetVal)[len] = 0; // last char, null terminator
}; // intttoa

As you might have suspected, this function converts an integer to character string. First, we determine if the number is negative and retrieve its length with the help of the previous function. We allocate a character string with the length determined and start appending a character to the string.

You can use it like so:

char* mystring; // don't allocate, don't do anything
inttoa(42, &mystring); // simply pass it to the function

// do things with the string

free(mystring); // you *do* have to free() the string though

No Comments | Tags: Tagged with:

Flattening Multidimensional Arrays

11 October 2008 - 16:25, By E. Luten
Edit: Thank you, fixitman for the insightful comment; the code has been fixed to work with non-square arrays as well.

In an effort to produce a better performing multidimensional array, I would like to share the following with you. Say we have a Matrix (or multidimensional array) of 5 x 5 integer elements, M. In order to allocate such an array in C++, we use the following code:

const size_t Width = 5;
const size_t Height = 5;
int** Array = new int*[Height]; // 2-Dimensional

for (size_t i = 0; i < Height; ++i)
	Array[i] = new int[Width];

// etcetera.

for (size_t i = 0; i < Height; ++i)
	delete[] Array[i];
delete[] Array;

In order to counter-act this looping behavior, which, in many cases will slow down the program upon allocation and freeing of memory (due to the loops), the array may be flattened like so:

const size_t Width = 5;
const size_t Height = 5;
int* Array = new int[Width*Height]; // 1-Dimensional

// etcetera.

delete [] Array;

Thus causing fewer allocations than before, and eliminating loops entirely. You might think that the array is entirely out of order, and no logical index can be obtained for selecting e.g.: Array[2][3];. This is where a simple calculation comes in handy.

AX,Y = (Y x Width) + X

With this calculation we can select our element by doing the following:

[...]
// desired position:
const size_t X = 2;
const size_t Y = 3;
[...]
int RequestedInteger = Array[(Y*Width)+X];
O 0 1 2 3 4 X
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24
Y

This works because if we visualize our flattened array’s indexes in a table (right →), we can see that if we take Y (3) and multiply it by the Width (5) we get the appropriate first index of the row (15, or 0,3). If we add X (2) we have selected index 17, which is the index we want (X2, Y3).

This implementation is faster because we only allocate one single block of memory of X*Y instead of X*Y blocks of memory. The disadvantage of this is that to select any index from the array, you will have to calculate the expression, but this is a minor operation compared to the allocation/de-allocation loops.

1 Comment | Tags: Tagged with:

CriticalSection wrapper class

22 August 2008 - 11:09, By E. Luten

What: A C++ wrapper around both WINAPI (Microsoft Windows) and PThreads (POSIX threads) functionality.
Why: To abstract cross platform functionality.
Remarks: On windows, CRITICAL_SECTION objects cannot be shared cross-process. This means that the class is tied to your application or DLL process. Comments are in Doxygen/Javadoc style.

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <pthread.h>
#endif

/**
 * @class A wrapper-class around Critical Section functionality, WIN32 & PTHREADS.
 */
class CriticalSection
{
public:
	/**
	 * @brief CriticalSection class constructor.
	 */
	explicit CriticalSection(void)
	{
	#ifdef _WIN32
		if (0 == InitializeCriticalSectionAndSpinCount(&this->m_cSection, 0))
			throw("Could not create a CriticalSection");
	#else
		if (pthread_mutex_init(&this->m_cSection, NULL) != 0)
			throw("Could not create a CriticalSection");
	#endif
	}; // CriticalSection()

	/**
	 * @brief CriticalSection class destructor
	 */
	~CriticalSection(void)
	{
		this->WaitForFinish(); // acquire ownership
	#ifdef _WIN32
		DeleteCriticalSection(&this->m_cSection);
	#else
		pthread_mutex_destroy(&this->m_cSection);
	#endif
	}; // ~CriticalSection()

	/**
	 * @fn void WaitForFinish(void)
	 * @brief Waits for the critical section to unlock.
	 * This function puts the waiting thread in a waiting
	 * state.
	 * @see TryEnter()
	 * @return void
	 */
	void WaitForFinish(void)
	{
		while(!this->TryEnter())
		{
		#ifdef _WIN32
			Sleep(1); // put waiting thread to sleep for 1ms
		#else
			usleep(1000); // put waiting thread to sleep for 1ms (1000us)
		#endif
		};
	}; // WaitForFinish()

	/**
	 * @fn void Enter(void)
	 * @brief Wait for unlock and enter the CriticalSection object.
	 * @see TryEnter()
	 * @return void
	 */
	void Enter(void)
	{
		this->WaitForFinish(); // acquire ownership
	#ifdef _WIN32
		EnterCriticalSection(&this->m_cSection);
	#else
		pthread_mutex_lock(&this->m_cSection);
	#endif
	}; // Enter()

	/**
	 * @fn void Leave(void)
	 * @brief Leaves the critical section object.
	 * This function will only work if the current thread
	 * holds the current lock on the CriticalSection object
	 * called by Enter()
	 * @see Enter()
	 * @return void
	 */
	void Leave(void)
	{
	#ifdef _WIN32
		LeaveCriticalSection(&this->m_cSection);
	#else
		pthread_mutex_unlock(&this->m_cSection);
	#endif
	}; // Leave()

	/**
	 * @fn bool TryEnter(void)
	 * @brief Attempt to enter the CriticalSection object
	 * @return bool(true) on success, bool(false) if otherwise
	 */
	bool TryEnter(void)
	{
		// Attempt to acquire ownership:
	#ifdef _WIN32
		return(TRUE == TryEnterCriticalSection(&this->m_cSection));
	#else
		return(0 == pthread_mutex_trylock(&this->m_cSection));
	#endif
	}; // TryEnter()

private:
#ifdef _WIN32
	CRITICAL_SECTION m_cSection; //!< internal system critical section object (windows)
#else
	pthread_mutex_t m_cSection; //!< internal system critical section object (*nix)
#endif
}; // class CriticalSection

No Comments | Tags: Tagged with:

One to watch: MSDN Code Gallery

2 April 2008 - 9:05, By E. Luten

While reading Betsy Aoki’s blog I stumbled upon her post about Gotdotnet being dead. I’m not crying about it, I barely knew that site, but when you go to the old URL you’ll be presented with what seems to be Microsoft’s implementation of a resource dump: the MSDN Code Gallery — which is pretty neat.

Sure, there are only 4 C++ related things so far but if you’re a .NET programmer this site is pretty nifty, it even allows you to post your own snippets or host your own discussion. Of course there’s a huge license you’ll have to obey to and you have to donate your firstborn to Microsoft before posting anything… but that’s besides the point ;)

No Comments | Tags: Tagged with: