1.把一个字符串转化为整数:比如“12345”->12345
-
#include <stdio.h>
-
#include <windows.h>
-
#define MAX_INT 0x7FFFFFFF
-
#define MIN_INT 0x80000000
-
-
typedef enum status{
-
VALID=0,//合法
-
INVALID,//非法
-
}status_t;
-
-
int str_to_int_core(char *int_str, status_t *s, int symbol)//判断输入的字符是否合法,是则转
-
{
-
long long num = 0;
-
while (*int_str != '\0'){
-
if (*int_str >= '0' && *int_str <= '9'){
-
num = num * 10 + symbol*(*int_str - '0');
-
}
-
else{
-
*s = INVALID;
-
return 2;
-
}
-
int_str++;
-
}
-
if ( (symbol == 1 && num > MAX_INT) || \
-
(symbol == -1 && num < (signed int)MIN_INT))//输入的字符虽然合法,但要判断int能否装下
-
{
-
printf("num is overflow!\n");
-
*s = INVALID;
-
return 3;
-
}
-
return (int)num;
-
}
-
int str_to_int(char *int_str, status_t *s)
-
{
-
*s = VALID;
-
if (NULL == int_str || *int_str == '\0' || NULL == s){
-
*s = INVALID;
-
return 1;
-
}
-
int symbol = 1;
-
if (*int_str == '+'){
-
int_str++;
-
}
-
else if (*int_str == '-'){
-
symbol = -1;
-
int_str++;
-
}
-
else{
-
//DO NOTHING
-
}
-
return str_to_int_core(int_str, s, symbol);
-
-
}
-
-
int main()
-
{
-
char int_str[] = "-123456";
-
status_t s;
-
int ret_int = str_to_int(int_str, &s);
-
if (s == VALID){
-
printf("result int : %d\n", ret_int);
-
}
-
else{
-
printf("errno code : %d\n", ret_int);
-
}
-
system("pause");
-
return 0;
-
}
2.把一个二进制数的一位置1或置0,其它为保持不变
-
#include <stdio.h>
-
#include <windows.h>
-
void show_bit(unsigned char bit_8)
-
{
-
int i = 0;
-
unsigned char flag = 0x80; //1000 0000
-
for (; i < sizeof(unsigned char)* 8; i++){
-
if (flag & bit_8){
-
printf("1");
-
}
-
else{
-
printf("0");
-
}
-
flag >>= 1;
-
}
-
printf("\n");
-
}
-
-
#define _ZERO_ 0//for flag
-
#define _ONE_ 1
-
void bit_set(unsigned char *p_data, unsigned char pos, int flag)
-
{
-
if (flag == _ZERO_)
-
{
-
*p_data &= ~(0x1 << pos);
-
}
-
else if (flag == _ONE_)
-
{
-
*p_data |= (0x1 << pos);
-
}
-
else
-
{
-
return;
-
}
-
}
-
-
int main()
-
{
-
unsigned char tmp = 0x0f;
-
show_bit(tmp);
-
bit_set(&tmp, 7, _ONE_);
-
show_bit(tmp);
-
bit_set(&tmp, 0, _ZERO_);
-
show_bit(tmp);
-
system("pause");
-
return 0;
-
}
阅读(1221) | 评论(0) | 转发(0) |