Introduction
Recently I was working on a project to store binary data to a text file and
read it again. The solution I thought to be simple and fast was to convert each
byte into hexadecimal format and then again convert it to binary format. There
are other methods such as Base64 encoding to do it but I was short of time. So I
created two functions fully UNICODE compatible.
The following functions convert to any number basis such as binary, octal,
decimal, hex or in range of 2 to 36.
int StrToNum(const TCHAR *udata, int datalen, int base)
: Convert any string to relevant numerical base.
TCHAR* __fastcall NumToStr(TCHAR
*RetData, long number, int base)
:
Converts any number to string in the desired base.
Here is the complete code with examples
#include <windows.h>
#include <iostream.h>
#include <tchar.h>
int __fastcall StrToNum(const TCHAR *udata, int udatalen, int base)
{
long index;
const TCHAR numdigits[] = TEXT("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
long digitValue = 0;
long RetVal = 0;
TCHAR digits[sizeof(numdigits)+1];
TCHAR *dataVal;
TCHAR data[512] ;
_tcscpy(data, udata);
_tcsupr(data);
ZeroMemory(digits, sizeof(digits));
_tcsncpy(digits, numdigits, base);
for(index = 0; index < udatalen; index++)
{
dataVal = _tcschr(digits, data[index] );
if(dataVal != 0 )
{
digitValue = long(dataVal - digits);
RetVal = RetVal * base + digitValue;
}
}
return RetVal;
}
TCHAR* __fastcall NumToStr(TCHAR *RetData, long number, int base)
{
long index = 0;
const TCHAR numdigits[] = TEXT("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
long digitValue = 0;
TCHAR digits[sizeof(numdigits) + 1];
TCHAR RetVal[512];
TCHAR CurVal = 0;
ZeroMemory(RetVal, sizeof(RetVal));
if(base < 2 || base > 36 ) return NULL;
ZeroMemory(digits, sizeof(digits));
_tcsncpy(digits, numdigits, base);
while(number)
{
digitValue = number % base;
number = number base;
RetVal[index++] = digits[digitValue];
}
ZeroMemory(RetData, _tcslen(RetVal)+1);
int i = 0;
for(index = _tcslen(RetVal) - 1; index > -1; index--)
{
RetData[i++] = RetVal[index];
}
return RetData;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
TCHAR Data[128];
ZeroMemory(Data, sizeof(Data));
NumToStr(Data, 1123, 10);
cout << StrToNum(Data, _tcslen(Data), 10) << endl;
return 0;
}
Note: This code can also be used as a simple form of encryption. Here is a
simple eg.:-
_tcscpy(Data, TEXT("1024") );
int Number = StrToNum(Data, _tcslen(Data), 10);
NumToStr(Data, Number, 27);
cout << TEXT("Modified String is ") << Data << endl;
Number = StrToNum(Data, _tcslen(Data), 27);
NumToStr(Data, Number, 10);
cout << TEXT("Original Number is ") << Data << endl;