32位无符号整数转换为二十四进制编码串(C语言实现)

时间:2022-06-16 10:18:09

================================================================================
= 题目: 32位无符号整数转换为二十四进制编码串
= 日期: 2017.03.27
================================================================================

*. 题目描述
把32位无符号整数转换为二十四进制编码串, 其中二十四进制编码串为无符号值。
二十四进制码表定义如下:
--------------------------
十进制 二十四进制码
--------------------------
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 F
14 H
15 K
16 M
17 P
18 S
19 T
20 U
21 W
22 X
23 Y
--------------------------

*. 示例
--------------------------
十进制值 二十四进制串
--------------------------
0 0
19 T
24 10
46 1X
96 40
383 KY
220633 KY11
127084934 KY11FH
--------------------------

 

/*
32位无符号整数转换为二十四进制编码串, 其中:
参数:
value 32位无符号整数值
str 存放二十四进制编码串的缓冲区
size str 缓冲区的尺寸
返回值:
>0 转换成功, 返回转换后的编码串长度
0 转换失败, 缓冲区尺寸太小
-1 转换失败, 参数不合法
*/
static const char scale24[24] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'F', 'H', 'K', 'M', 'P', 'S', 'T', 'U', 'W', 'X', 'Y'};

int U32ToC24(unsigned int value, char* str, int size)
{
int result = -1;
int nSize = 0;
unsigned
int idxVal = value; // 值或商
char* pStrEnd = str;

if ( str!=NULL && size>0 ) // 参数合法,开始进行转换
{
// 获得尺寸
do{
idxVal
/= 24;
nSize
++;
}
while (idxVal > 0);

if (nSize > size)
{
result
= 0; // 缓冲区尺寸太小
}
else
{
// 填充编码缓冲区
idxVal = value;
pStrEnd
= str+nSize-1;
do{
*pStrEnd = scale24[idxVal%24];

idxVal
/= 24;
pStrEnd
--;
}
while (idxVal > 0);
result
= nSize; // 编码串长度
}
}

return result;
}