1.atoi的模拟实现
头文件
#include <stdlib.h>
atoi的作用就是将字符串转换为整形
//my_atoi(NULL)//异常
//my_atoi("")//异常
//my_atoi(" +123")//正常
//my_atoi("-123")//正常
//my_atoi("123abc")//异常
//my_atoi("1111111111111111111111111")//异常
//my_atoi("-1111111111111111111111111")//异常
#include <stdlib.h>
#include<stdio.h>
#include <limits.h>
#include <ctype.h>
enum Status
{
true,
false
};
enum Status status = false;
int ATOI(char* arr)
{
if (arr == NULL)//判断是否为空
{
return 0;
}
if (*arr == '\0')//判断字符串是否为空
{
return 0;
}
while (isspace(*arr))//判断是否有空格
{
arr++;
}
int flag = 1;
if (*arr == '+')//判断加号
{
flag = 1;
arr++;
}
if (*arr == '-')//判断减号
{
flag = -1;
arr++;
}
long long ret = 0;//为了后面判断是否数据过大
while (isdigit(*arr))//判断是否为数字
{
ret = ret * 10 + flag * (*arr - '0');
arr++;
}
if (ret<INT_MIN || ret>INT_MAX)
{
return 0;
}
if (*arr == '\0')
{
status = true;
return (int)ret;
}
else
{
return (int)ret;
}
}
int main()
{
char arr[20] = {0};
scanf("%s",arr);
int ret=ATOI(arr);
if (status == true)
{
printf("转换成功:%d",ret);
}
else
{
printf("转换失败:%d",ret);
}
return 0;
}
##########################################################
##########################################################
##########################################################
##########################################################
2.offsetof的模拟实现
头文件
#include<stddef.h>
offsetof是用来查看结构体成员偏移量的函数
#include<stdio.h>
#define OFFSETOF(type_t,type_name) (size_t)&(((type_t*)0)->type_name)
//将结构体首地址设置为0,则结构体成员 的地址 就是对应的偏移量
struct test
{
int a;
char b[10];
float c;
};
int main()
{
int ret=OFFSETOF(struct test,c);
printf("%d",ret);
return 0;
}
####################################################################
####################################################################
####################################################################
####################################################################
3.使用宏来实现一个数的二进制奇数偶位进行交换
#define Swap(a) ((a&0XAAAAAAAA)>>1)+((a&0X55555555)<<1)
int main()
{
int a = 0;
scanf("%d",&a);
int ret=Swap(a);
printf("%d",ret);
return 0;
}
########################################################################
########################################################################