-
-
Save wilkie/441657 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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