Stránka 1 z 1

Rozšíření STD lib - unsigned int std::atou(const char *_Str)

PříspěvekNapsal: 03 leden 2013 06:12:02
od Wlezley
unsigned int std::atou(const char *_Str);
char * std::utoa(unsigned int _Val, char * _DstBuf, int _Radix);

Před nějakou dobou jsem hrozně nadával na to, že knihovna STD neobsahuje převod textových řetězců (stringů) do unsigned int (celočíselný typ bez znaménka). Rozhodl jsem se o rozšíření namespace (jmenného prostoru) STD o funkci atou. Když už jsem byl v tom, udělal jsem i převod zpět, tedy utoa. :flex:

StdExtend.cpp
RAW CODE
/***
* (c)2012 Ladislav Alexa - WLEZLEY.EU Simulation Software
*/


#include "StdExtend.h"
#include <ctype.h>

unsigned int std::atou(const char *_Str)
{
unsigned int u = 0;
for(short int offset = 0; _Str[offset] != '\0'; offset++)
{
if(!isdigit(_Str[offset])) return 0;
else u = u * 10 + (_Str[offset] - '0');
}
return u;
}

char * std::utoa(unsigned int _Val, char * _DstBuf, int _Radix)
{
char temp[17];
int digit, str_loc = 0, temp_loc = 0;

do {
digit = (unsigned int)_Val % _Radix;
if (digit < 10) temp[temp_loc++] = digit + '0';
else temp[temp_loc++] = digit - 10 + 'A';
_Val = (unsigned int)_Val / _Radix;
} while (_Val != 0);

temp_loc--;

// reverse
while (temp_loc >= 0) { _DstBuf[str_loc++] = temp[temp_loc--]; }
_DstBuf[str_loc] = 0;
return _DstBuf;
}


StdExtend.h
RAW CODE
/***
* (c)2012 Ladislav Alexa - WLEZLEY.EU Simulation Software
*/


#ifndef __STD_EXTEND_H__
#define __STD_EXTEND_H__

#include <stdio.h>
#include <stdlib.h>

namespace std
{
unsigned int atou(const char *_Str);
char * utoa(unsigned int _Val, char * _DstBuf, int _Radix);
};

#endif /* __STD_EXTEND_H__ */