C语言 转换10进制数字到26进制(EXCEL 列名)

前两天项目用到一个将10进制的索引号转换成EXCEL 列名的问题 以下做个小工具专门 做转换,上代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*****************************************
 * filename:itoletter.c
 * description: convert the index 10 based (start from 1) to 26 based letter
 *author:Dave Ning
 * date:Sep 24 2011
 * ****************************************/
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
 
//#define char unsigned char
char * reverse(char * str, size_t len);
char * convert(unsigned int index,char *letter)
{
 assert( letter != NULL);
 
 char list[] = {'Z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'
 ,'P','Q','R','S','T','U','V','W','X','Y','Z'};
 char buffer[200] = {0};
 
 unsigned short pos = 0;
 
 //if (index == 0)
 //{
 //可以增加针对输入为0的参数的处理(EXCEL中编号从1开始)
 //}
 
 while(0 != (index / 26))
 {
 buffer[pos] = list[index % 26];
 ++pos;
 index = (index - 1) / 26;           
 }
 
 if(index != 0)
 {
 buffer[pos] = list[index];
 }
 
 return strcpy(letter,reverse(buffer,strlen(buffer)));
 
}
 
char * reverse(char * str, size_t len)
{
 assert(str != NULL);
 
 char tmp = '0';
 
 for(size_t i = 0; i < len / 2; ++i)
 {
 tmp = str[i];
 str[i] = str[len - i - 1];
 str[len - i - 1] = tmp;
 }
 
 return str;       
}
 
int main(int argc, char *argv[])
{
 if(argc == 1)
 {
 printf("Usage:\n\titoletter index\te.g: itoletter 26 \
 \n\tby Dave Ning\n");
 return 0;
 }
 
 int i = atoi(argv[1]);
 char letter[200] = {0};
 convert(i, letter);
 printf("the %d letter is :%s\n",i,letter);
 return 0;
}

运行结果截图 :

结果

此条目发表在未分类分类目录。将固定链接加入收藏夹。