101 lines
1.9 KiB
C
101 lines
1.9 KiB
C
|
/*
|
||
|
* convert_ops.c
|
||
|
*
|
||
|
* Created on: Aug 27, 2011
|
||
|
* Author: Tiberiu
|
||
|
*/
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
const string _Numbers = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||
|
|
||
|
int32 ConvertIntToString (string buffer, int32 number, int32 base)
|
||
|
{
|
||
|
if (base > 36 || base < 2) return 0;
|
||
|
|
||
|
int32 len = numlen (number, base), beg = 0, i;
|
||
|
uint32 n = (uint32) number;
|
||
|
|
||
|
// If number is negative and in base 10, we put a '-' in front
|
||
|
if (number < 0 && base == 10) buffer[beg++] = '-';
|
||
|
|
||
|
// Put every digit in string
|
||
|
for (i = len-1; i>=beg; i--)
|
||
|
{
|
||
|
buffer[i] = _Numbers[n % base];
|
||
|
n /= base;
|
||
|
}
|
||
|
|
||
|
buffer[len] = 0;
|
||
|
return number;
|
||
|
}
|
||
|
|
||
|
uint32 ConvertUIntToString (string buffer, uint32 number, int32 base)
|
||
|
{
|
||
|
if (base > 36 || base < 2) return 0;
|
||
|
|
||
|
int32 len = unumlen (number, base), i;
|
||
|
|
||
|
// Put every digit in string
|
||
|
for (i = len-1; i >= 0; i--)
|
||
|
{
|
||
|
buffer[i] = _Numbers[number % base];
|
||
|
number /= base;
|
||
|
}
|
||
|
|
||
|
buffer[len] = 0;
|
||
|
return number;
|
||
|
}
|
||
|
|
||
|
int32 ConvertStringToInt (string buffer)
|
||
|
{
|
||
|
int8 negative = (buffer[0] == '-');
|
||
|
int32 pos = (buffer[0] == '-' );
|
||
|
|
||
|
int32 number = 0;
|
||
|
|
||
|
while (IsDigit(buffer[pos]))
|
||
|
{
|
||
|
number = number*10 + (buffer[pos] - '0');
|
||
|
pos++;
|
||
|
}
|
||
|
|
||
|
if (negative) return -number;
|
||
|
return number;
|
||
|
}
|
||
|
|
||
|
uint32 ConvertStringToUInt (string buffer)
|
||
|
{
|
||
|
int32 pos = 0;
|
||
|
int32 number = 0;
|
||
|
|
||
|
while (IsDigit(buffer[pos]))
|
||
|
{
|
||
|
number = number*10 + (buffer[pos] - '0');
|
||
|
pos++;
|
||
|
}
|
||
|
|
||
|
return number;
|
||
|
}
|
||
|
|
||
|
uint32 ConvertStringToIntHex (string buffer)
|
||
|
{
|
||
|
int32 pos = 0;
|
||
|
uint32 number = 0;
|
||
|
|
||
|
// Skip first 2 digits if it is in format 0xXXXX...
|
||
|
if (buffer[1] == 'x' || buffer[1] == 'X') pos = 2;
|
||
|
|
||
|
while (IsHexDigit(buffer[pos]))
|
||
|
{
|
||
|
number = number*0x10;
|
||
|
|
||
|
if (IsDigit(buffer[pos])) number += buffer[pos] - '0';
|
||
|
else if (buffer[pos] >= 'a' && buffer[pos] <= 'f') number += 10 + buffer[pos] - 'a';
|
||
|
else if (buffer[pos] >= 'A' && buffer[pos] <= 'F') number += 10 + buffer[pos] - 'A';
|
||
|
|
||
|
pos++;
|
||
|
}
|
||
|
|
||
|
return number;
|
||
|
}
|