Skip to content

Instantly share code, notes, and snippets.

@wilkie
Forked from LindseyB/base26.c
Created June 17, 2010 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilkie/441657 to your computer and use it in GitHub Desktop.
Save wilkie/441657 to your computer and use it in GitHub Desktop.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
char* toBase26(int num) {
char* str;
int length = 1;
int tmp = num;
// Determine length
while(tmp > 0) {
tmp--;
tmp /= 26;
length++;
}
// Allocate string
str = malloc(length + 1);
char* temp = str + length;
*temp = '\0';
while(num > 0) {
// 'A' has meaning, even though it represents zero:
num--;
// Figure out the character and add it to the string
temp--;
*temp = (num % 26) + 'A';
// Go to next base26 digit
num /= 26;
}
// Return result
return temp;
}
int toBase10(char* str) {
int len = strlen(str);
int num = 0;
int i;
int val;
// Remember to start at end of string
for(i = 0; i < len; i++) {
// Shift the digit
num = num * 26;
// Add the value
val = str[i] - 'A';
// Remember the A has meaning rule!
val++;
// Add
num += val;
}
return num;
}
int main() {
printf("%s\n", toBase26(28));
printf("%d\n", toBase10("AB"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment