JZsdk_string.c
2.3 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdio.h>
#include "JZsdk_string.h"
/*
* 用于字符串转int型
*/
int JZsdk_String_str_to_int(const char *str)
{
int temp = 0;
const char *ptr = str; //ptr保存str字符串开头
if (*str == '-' || *str == '+') //如果第一个字符是正负号,
{ //则移到下一个字符
str++;
}
while(*str != 0)
{
if ((*str < '0') || (*str > '9')) //如果当前字符不是数字
{ //则退出循环
break;
}
temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值
str++; //移到下一个字符
}
if (*ptr == '-') //如果字符串是以“-”开头,则转换成其相反数
{
temp = -temp;
}
return temp;
}
/*
* int型转字符串
*/
void JZsdk_String_int_to_str(int n, char *str)
{
char buf[10] = "";
int i = 0;
int len = 0;
int temp = n < 0 ? -n: n; // temp为n的绝对值
if (str == NULL)
{
return;
}
while(temp)
{
buf[i++] = (temp % 10) + '0'; //把temp的每一位上的数存入buf
temp = temp / 10;
}
len = n < 0 ? ++i: i; //如果n是负数,则多需要一位来存储负号
str[i] = 0; //末尾是结束符0
while(1)
{
i--;
if (buf[len-i-1] ==0)
{
break;
}
str[i] = buf[len-i-1]; //把buf数组里的字符拷到字符串
}
if (i == 0 )
{
str[i] = '-'; //如果是负数,添加一个负号
}
}
/*
* longlong型转字符串型
*/
size_t JZsdk_String_longlong_to_str(char *s, long long value,int radix)
{
char *p, aux;
unsigned long long v;
size_t l;
/* Generate the string representation, this method produces
* an reversed string. */
v = (value < 0) ? -value : value;
p = s;
do {
*p++ = '0' + (v % radix); // 2
v /= radix; // 2
} while (v);
if (value < 0) *p++ = '-';
/* Compute length and add null term. */
l = p - s;
*p = '\0';
/* Reverse the string. */
p--;
while (s < p) {
aux = *s;
*s = *p;
*p = aux;
s++;
p--;
}
return l;
}