here's my integer conversion algorithm, from base 10 to any base 2-36. you could modify it to work with floating point nubmers, if you want to. let me know if you make any successful modifications.
(PS: sorry for total lack of comments)
source in C:
Code:
/*Functions:
toch - integer to character, E.G 10 becomes A, 15 becomes F....
toi - reverse of toch. (character to integer)
leng - my own strlen. because i felt like it.
revstr - flips a string. asdf becomes fdsa.
itob - integer to base (integer, base)
btoi - base to integer (integer as string, base converting FROM)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char toch(int w);
int leng(char* str);
void revstr(char* str);
char* itob(int n, int r);
int btoi(char* num, int r);
char toch(int w) {
if (w > 9) return (w + 55);
else return (w + 48);
}
int toi(char w) {
if (w > 64) return (w - 55);
else return (w - 48);
}
int leng(char* str) {
int x;
for (x = 0; str[x] != 0; x++) {}
return x;
}
void revstr(char* str) {
char tmp;
int l = leng(str), l2 = l - 1, ong;
for (ong = 0; ong < (l / 2); ong++) {
tmp = str[ong];
str[ong] = str[l2 - ong];
str[l2 - ong] = tmp;
}
}
char* itob(int n, int r) {
char* tmpstr = malloc(sizeof(char) * 1024);
int m;
for (m = 0; (n % (int)pow(r, m)) != n; m++) {
tmpstr[m] = toch((n % (int)pow(r, m + 1)) / (int)pow(r, m));
n -= n % (int)pow(r, m + 1);
}
tmpstr[m+1] = toch((n % (int)pow(r, m+1)) / (int)pow(r, m));
revstr(tmpstr);
return tmpstr;
}
int btoi(char* num, int r) {
int l = leng(num), ans = 0, ong;
for (ong = 1; l - ong >= 0; ong++) {
ans += toi(num[l - ong]) * (int)pow(r, ong - 1);
}
return ans;
}
and in C++:
Code:
/* there are some unused functions i think.... and they're not perfect.
the ones that are there - you can figure them out, they're like the ones from the C version*/
#include <iostream>
#include <cmath>
using namespace std;
char toch(int w) {
if (w > 9) return (w + 55);
else return (w + 48);
}
int toi(char w) {
if (w > 64) return (w - 55);
else return (w - 48);
}
string revstr(string str) {
char tmp;
int l = str.length(), l2 = l - 1, ong;
for (ong = 0; ong < (l / 2); ong ++) {
tmp = str[ong];
str[ong] = str[l2 - ong];
str[l2 - ong] = tmp;
}
return str;
}
string tostr(char x) {
string ans = "" + x;
return ans;
}
string itob(int n, int r) {
string blah;
int m;
char tmp;
int l, l2, ong;
for (m = 0; (n % (int)pow((float)r, (float)m)) != n; m++) {
blah += toch((n % (int)pow((float)r, (float)(m + 1))) / (int)pow((float)r, (float)m));
n -= n % (int)pow((float)r, (float)(m + 1));
}
blah += toch((n % (int)pow((float)r, (float)(m + 1))) / (int)pow((float)r, (float)m));
return revstr(blah);
}
int btoi(string num, int r) {
int l = num.length(), ans = 0, ong;
for (ong = 1; l - ong >= 0; ong++)
ans += toi(num[l - ong]) * (int)pow((float)r, (float)(ong - 1));
return ans;
}
Please give me credit if you decide to use these..... also, if you manage to get it to work with floating points (i haven't tried yet) post results here!