目录
一.整型转字符型my_itoa函数
1.功能点实现
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>
char* my_itoa(int value, char* buff, int radix) {
assert(buff != NULL);
int left = 0, index = 0,flag=0;
const char* temp = "0123456789abcdefghijklmnopqrstuvwxyz";
if (value < 0 && radix == 10) {
buff[index++] = '-';
value *= -1;
flag = 1;
}
unsigned int unsigned_value=(unsigned int)value;//将value从有符号类型转换成无符号类型
while (unsigned_value != 0) {
left = unsigned_value % radix;
buff[index++] = temp[left];
unsigned_value /= radix;
}
for (int j = 0; j < (index + 1) / 2; j++) {
int tmp = buff[j+flag];
buff[j+flag] = buff[index - j - 1];
buff[index - j - 1] = tmp;
}
return buff;
}
int main() {
char buff[100] = { 0 };
printf("%s\n", my_itoa(10, buff, 2));
return 0;
}
2. 无符号型
如果把八位数据当做有符号型来看待,第一位数字为符号位,如:1111 1111 第一位为符号位值为-127;如果把八位数值当做无符号型来看待,则没有符号位,如:1111 1111值为255。
unsigned来表示无符号,对于char,int,short,long等类型可以使用无符号类型来修饰,float,double浮点类型不可以用无符号类型来修饰。
有符号类型转为无符号类型运算:
注意:1.有符号和无符号的算术运算;2.有符号和无符号的比较运算;
在C语言操作中,如果遇到无符号数与有符号数之间的算术操作,编译器会自动转化为无符号数来处理;
有符号数和无符号数在进行比较运算时,有符号数因式转换成无符号数(底层的补码不变)
二.字符型转整型my_atoi函数
一.功能点实现
“123”转为123;“+123”转为123;“-123”转为-123;“+++123”转为123;“ 123 ”转为123;
“+-+++123”转为-123;“123abc456”转为123;“abc123”转为0。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<assert.h>
//统计字符个数
int GetBit(const char* str) {
int count = 0;
while (*str != '\0') {
if (isdigit(*str))
{
count++;
}
else if (isblank(*str) || *str == '-' || *str == '+') {
str++;
continue;
}
else {
break;
}
str++;
}
return count;
}
//字符转整形的功能实现
int my_atoi(const char* str) {
int count = GetBit(str);
int result = 0,flag=1;
while (*str != '\0') {
if (*str == ' ' || *str == '+') {
str++;
continue;
}
else if (*str == '-') {
flag *= -1;
}
else {
result += (*str -'0') * (int)pow(10, --count);
}
str++;
}
return result*flag;
}
//主函数测试结果
int main() {
char arr[] = "--123";
printf("%d\n", my_atoi(arr));
}